flutter - Flutter中的TextFormField验证

标签 flutter dart

我正在开发Flutter TextFormField。我想在TextFormField下面显示一条错误消息,但是当我调试时出现此错误

The method 'validate' was called on null. Receiver: null Tried calling: validate()


    class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


  TextEditingController _titleController;
  TextEditingController _descriptionController;
  final _formKey = GlobalKey<FormState>();
 @override
  void initState() {
    super.initState();

    _titleController = new TextEditingController(text: widget.products.adTitle);
    _descriptionController = new TextEditingController(text: widget.products.description); @override
  Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("Products")
    ),
    body: Container(
      margin: EdgeInsets.all(15.0),
      alignment:  Alignment.center,
      key: _formKey,
      child: Column(
        children: <Widget>[
          TextFormField(
            controller: _titleController,
            decoration: InputDecoration(labelText: 'Title'),
            validator: (text) {
                if (text == null || text.isEmpty) {
                  return 'Text is empty';
                }
                return null;
              },
         RaisedButton(
            child: (widget.products.id != null)? Text('Update') : Text('Add'),
            onPressed:(){ 
               if (_formKey.currentState.validate()) {
                 child: Text('Submit');
               }

最佳答案

为了使用validate函数,您的Column应该包装在Form中

Container(
   margin: EdgeInsets.all(15.0),
   alignment: Alignment.center,
   child: Form(
         key: _formKey,
         child: Column(children: <Widget>[
               TextFormField(
                  controller: _titleController,
                  decoration:InputDecoration(labelText: 'Title'),
                              validator: (text) {
                                if (text == null || text.isEmpty) {
                                  return 'Text is empty';
                                }
                                return null;
                              },
               )
              ]))),

关于flutter - Flutter中的TextFormField验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61799266/

相关文章:

dart - <输入类型='date'>选择日期时Dartium崩溃

events - 处理聚合物元素中调整大小事件的最佳实践是什么?

flutter - Razorpay抖动1.1.4 Gradle构建异常

list - 如何在Dart中以空对象结尾对List <File>进行排序

firebase - flutter 问题 : type 'Timestamp' is not a subtype of type 'DateTime'

Flutter web - 如何监听打开的抽屉状态并关闭它

flutter - build.yaml 中是否有 build_extensions 规则将所有生成的 Flutter 模型输出到公共(public)目录中?

flutter - Flutter Visibility Toggle无法正常工作

macos - 如何发布一个用flutter编写的macos应用

dart - Flutter 中的可折叠列表小部件有哪些选项?