我有一個 Flutter 應用程式,我想添加一個在打開應用程式時出現的頁面,要求用戶回答一個問題,例如世界上有多少個國家 - 答案已經存盤在應用程式中,以便如果答案正確, 答案被存盤,應用程式打開,此頁面不再出現,但如果答案錯誤,用戶仍留在此頁面上,他無法打開應用程式,直到他寫出正確的答案 任何有用的建議或示例?
更新:我創建了以下驗證頁面,用于檢查輸入的文本是否等于存盤的文本,如果為真,我使用flutter_secure_storage存盤文本現在我想知道如何將shared_preferences添加到我的代碼中?
class check extends StatefulWidget {
@override
_checkState createState() => _checkState();
}
class _checkState extends State<check> {
final formKey = GlobalKey<FormState>();
final verifierController = TextEditingController();
String storedvalue = '200';
@override
void initState() {
super.initState();
init();
}
Future init() async {
final realcode = await UserSecureStorage.getCodestored() ?? '';
setState(() {
this.verifierController.text = realcode;
});
}
Codecheck() async {
await UserSecureStorage.setUsername(verifierController.text);
if (storedvalue == verifierController.text) {
Navigator.of(context).pushReplacementNamed('/homeScreen');
}
else {
Navigator.of(context).pushReplacementNamed('/checkScreen');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(10),
child: Center(
child: Stack(
children: [
Align(
child: Text(
'how many countries are there in the world?',
.........
),
Align(
child: TextFormField(
.......
controller: verifierController,
)),
Align(
child: RaisedButton(
.........
onPressed: () async {
Codecheck();
},
..........
uj5u.com熱心網友回復:
您將檢查用戶的答案,如果正確,則在共享首選項中保存一個布林值,然后導航到應用程式主頁,每次打開應用程式時,您都會從共享首選項中檢查此布林值,如果為真,則不要t顯示問題,直接打開首頁,如果沒有,再顯示問題
uj5u.com熱心網友回復:
以一種非常簡單的方式,您可以使用SharedPreferences插件永久存盤您的問題的答案,例如
您可以存盤一個“問題”鍵,該鍵的值為“世界上有多少個國家? ”(可選)。您還存盤了一個值為“ 324 ”的“ answer ”鍵(世界上確切的國家數量)
然后你創建一個“ answer_found ”鍵,它將是一個布林值,如果是或否用戶正確回答問題,它將更新。
然后當應用程式啟動時,您將首先查詢“ answer_found ”鍵以查看其值是否為True。
如果該值為True,則不顯示問卷頁面,如果值為 false 或 null ,則顯示問卷頁面。
當用戶輸入答案時,只需將他的答案與首選項中“答案”鍵中包含的答案進行比較。如果正確,只需更新鍵“ answer_found ”即可。在相反的情況下什么都不做(或你想要的)
更新: 正如您所問,這里是代碼的摘錄。我把它做得盡可能簡單(雖然有點野蠻),這樣你就可以盡可能地理解這個機制,并且你可以隨心所欲地調整它。
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await SharedPreferences.getInstance().then((preferences) async {
//Optional key (and can put want you want)
//Store the question in preferences
await preferences.setString('question', 'how many countries are there in the world?');
//Store the answer
await preferences.setInt('answer', 324);
});
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool? questionAnswered;
@override
void initState() {
super.initState();
_getQuestionState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: home,
);
}
Widget get home {
if (questionAnswered == null) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
} else if (questionAnswered!) {
return const HomePage();
} else {
return const QuestionPage();
}
}
Future<void> _getQuestionState() async {
final preferences = await SharedPreferences.getInstance();
//obtaining the present value of 'answer_found' to know if the question has been answered (with a correct answer)
final isQuestionAnswered = preferences.getBool('answer_found') ??
false; //if the value is null, we set it to false (to avoid a NullException)
setState(() => questionAnswered = isQuestionAnswered);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Home Page'),
),
body: const Center(
child: Text('WELCOME'),
),
);
}
class QuestionPage extends StatefulWidget {
const QuestionPage({Key? key}) : super(key: key);
@override
State<QuestionPage> createState() => _QuestionPageState();
}
class _QuestionPageState extends State<QuestionPage> {
late final TextEditingController _answerTextController;
@override
void initState() {
super.initState();
_answerTextController = TextEditingController();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const Text('how many countries are there in the world?'),
TextField(
controller: _answerTextController,
decoration: const InputDecoration(hintText: 'Enter answer'),
),
ElevatedButton(
onPressed: () async {
//Convert the user's response to be in an integer type (because we want to make a comparison with an integer)
//The user's response will be null, if the user has not entered an integer
final userAnswer = int.tryParse(_answerTextController.text);
if (userAnswer != null) {
final preferences = await SharedPreferences.getInstance();
final storedAnswer = preferences.getInt('answer')!;
if (userAnswer == storedAnswer) {
preferences.setBool('answer_found', true);
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const HomePage()));
} else {
//Notify user that his answer was wrong or do some stuff (what you want)
}
} else {
//Do some stuff
}
},
child: const Text('Validate')),
],
),
),
);
}
}
我從未使用過 flutter_secure_storage 插件,但是按照我為您制作的代碼片段,我認為您可以重新調整它以使用 flutter_secure 存盤,推理和邏輯是相同的。
PS:您不必同時使用 shared_preferences 和 flutter_secure_storage 。您可以簡單地使用 flutter_secure_storage ,與 shared_preferences 不同,它為您提供安全的存盤空間(如其名稱所示),您只需實作相同的邏輯。
uj5u.com熱心網友回復:
我希望您將啟影片面作為要加載到應用程式中的第一個螢屏。
現在,當第一個螢屏將加載時。使第一個螢屏成為有狀態的。
這將允許您使用“initstate”方法。并且您知道將首先呼叫 initstate 方法來執行代碼。
initstate(){
/// in this case I am using "get_storage" to store the data in local.
GetStorage prefs = GetStorage("ApplicationName");
bool isAnswered = prefs.read("isAnsweredQuestion") ?? false;
if(isAnswered){
/// redirect to the other screen.
}else{
/// redirect to the screen where you have the questions
/// or open the dialog having questions.
}
super.initstate();
};
initstate 方法將在應用程式加載并執行啟影片面時第一次執行,并將檢查本地資料存盤。
如果用戶是第一次打開應用程式,那么本地資料將為空,我們使用空檢查運算子來處理它。
如果用戶已經回答了問題,那么我們將在本地存盤“true”。在這種情況下,我們會將用戶重定向到另一個螢屏。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/393796.html
上一篇:在容器顫動時制作漸變效果,
