我想制作一个测验应用程序,您可以在其中使用键盘输入答案。我现在已经尝试了很多事情,但是我的解决方案都没有帮助我。谁能帮我?
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new TextField(
decoration: InputDecoration(labelText:"put in the correct answer",
labelStyle: TextStyle(color: Colors.white)
),
key: _formKey,
autovalidate: true,
validator: (String value){
if (value.contains("test") ){
return "pleas more";
}else{
return null;}
}
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
onPressed: (){
if (_formKey.currentState.validate()){
debugPrint("The Answer is correct.");
}
},
),
),
],)
]
)
答案 0 :(得分:1)
您需要使用Form
,GlobalKey
和TextFormField
而非常规的TextField
来验证结果。
// create a GlobalKey
GlobalKey<FormState> _formKey = GlobalKey();
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Form( // create a form
key: _formKey, // assign key
child: TextFormField(
decoration: InputDecoration(labelText: "Your answer", labelStyle: TextStyle(color: Colors.white)),
autovalidate: true,
validator: (String value) {
if (value.contains("test")) {
return "pleas more";
} else {
return null;
}
}),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
child: Text("Validate"),
onPressed: () {
if (_formKey.currentState.validate()) {
debugPrint("The Answer is correct.");
}
},
),
),
],
),
);
}
答案 1 :(得分:0)
如果只有一个TextField
,则无需使代码变得如此复杂。
只需声明一个变量即可将TextEditingController
作为类变量(在类内任何代码块之外的任何位置)存储TextEditingController
并将其传递给您的controller
参数TextField
。
TextEditingController _controller = TextEditingController();
简化的解决方案代码:
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new TextField(
decoration: InputDecoration(labelText:"put in the correct answer",
labelStyle: TextStyle(color: Colors.white)
),
controller: _controller,
onSubmitted: (answer) {
if (answer.contains("test")) debugPrint("The answer is correct");}
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
onPressed: (){
if (_controller.text.contains("test")) debugPrint("The answer is correct");}
}
},
),
),
],)
]
)