【问题标题】:TextFormField validator, Error not visible on TextFormFieldTextFormField 验证器,错误在 TextFormField 上不可见
【发布时间】:2019-05-01 07:47:15
【问题描述】:

我正在尝试创建一个带列的表单。

喜欢,表单 => 列 => 文本字段,

TextFields 会有验证器。 此外,TextFields 也会有装饰。

但是当我点击 RaisedButton 时,我在 TextField 上找不到错误。 虽然 TextFormField 中的返回执行成功。 (我使用调试器检查过)

到目前为止,我参考的链接如下: https://www.youtube.com/watch?v=xiEYNzU4bDg

https://iirokrankka.com/2017/10/17/validating-forms-in-flutter/

https://medium.com/@nitishk72/form-validation-in-flutter-d762fbc9212c

下面是我的代码,请求帮我解决这个问题

import 'package:flutter/material.dart';

class Profile extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new ProfileState();
  } //createState closes here....
} //Profile closes here.....

class ProfileState extends State<Profile> {
  @override
  Widget build(BuildContext context) {
    final _formKey = GlobalKey<FormState>();

    return new Scaffold(
        appBar: new AppBar(title: new Text("Profile")),
        body: Form(
          key: _formKey,
          child: new Column(
            children: <Widget>[
              //Full Name TextGormFeild goes below....
              new TextFormField(
                  validator: (String value) {
                    if (value.isEmpty) {
                      return "Full name cannot be empty.";//Control comes here when I check using the Debugger.
                    } //if(value.isEmpty) closes here....
                  },
                  keyboardType: TextInputType.text,
                  textInputAction: TextInputAction.next,
                  maxLines: 1,
                  decoration: InputDecoration(
                      border: new OutlineInputBorder(
                          borderSide: new BorderSide(color: Colors.grey)),
                      hintText: "Enter name")),

              new RaisedButton(
                child: new Text("Test"),
                onPressed: () {
                  setState(() {
                    if (_formKey.currentState.validate()) {
                      print("Validations are correct.");
                    }
                  });
                },
              )
            ],
          ),
        )

        //,
        // helperText: "Enter full name"
        );
  } //build closes here.....

} //ProfileState closes here....

之前我使用 helperText,但我已经将其删除了。

【问题讨论】:

    标签: dart flutter flutter-layout


    【解决方案1】:

    尝试从您的 onPressed 中删除 setState

    setState(() {
    
    });
    

    只放

    if (_formKey.currentState.validate()) {
      print("Validations are correct.");
    }
    

    如下:

    onPressed: () {
        if (_formKey.currentState.validate()) {
          print("Validations are correct.");
        }
    },
    

    【讨论】:

    • 自过去 2 天以来,我一直被困在这一点上。谢谢@ibhavikmakwana
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2019-12-04
    • 1970-01-01
    • 2023-01-12
    • 2020-12-15
    • 1970-01-01
    • 2019-04-11
    相关资源
    最近更新 更多