gpt4 book ai didi

flutter - 在 Flutter 中显示 TextField 的错误文本

转载 作者:行者123 更新时间:2023-12-04 10:42:49 25 4
gpt4 key购买 nike

我正在构建一个带有 2 个输入的登录屏幕。我想在按下按钮时验证电子邮件地址。我的猜测是我必须让 View 知道值已更改。

按钮

   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),
);
}

最佳答案

如果你想验证用户输入,你应该检查表单和验证器。在表单中,您可以使用验证器来加速 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

关于flutter - 在 Flutter 中显示 TextField 的错误文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59847945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com