我正在构建2个输入的登录屏幕。按下按钮后,我想验证电子邮件地址。我的猜测是我必须让视图知道该值已更改。
按钮
RaisedButton(
color: Colors.blue,
textColor: Colors.white,
child: Text('Login'),
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(4)),
onPressed: () {
print('hey');
if (!EmailValidator.validate(_emailController.text)) {
_emailValid = false;
return;
}
// do login stuffs
},
)
文本字段
_textFieldWidget('Email', false, _emailController, TextInputType.emailAddress, _emailValid ? 'not valid' : null)
Widget _textFieldWidget(String label, bool obscureText,
TextEditingController controller, TextInputType type, String errorText) {
return new TextField(
obscureText: obscureText,
controller: controller,
keyboardType: type,
decoration: InputDecoration(
border: OutlineInputBorder(), labelText: label, errorText: errorText),
);
}
答案 0 :(得分:2)
如果要验证用户输入,则应签出表单和验证器。 在表单中,您可以使用验证器来简化TextFormField的操作-这是从flutter网站获取的示例:
// Create a Form widget.
class MyCustomForm extends StatefulWidget {
@override
MyCustomFormState createState() {
return MyCustomFormState();
}
}
// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
// Create a global key that uniquely identifies the Form widget
// and allows validation of the form.
//
// Note: This is a GlobalKey<FormState>,
// not a GlobalKey<MyCustomFormState>.
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
onPressed: () {
// Validate returns true if the form is valid, or false
// otherwise.
if (_formKey.currentState.validate()) {
// If the form is valid, display a Snackbar.
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('Processing Data')));
}
},
child: Text('Submit'),
),
),
],
),
);
}
}
有关更多信息,请访问flutter网站 https://flutter.dev/docs/cookbook/forms/validation