【问题标题】:Error: Method 'save' cannot be called on 'FormState?' because it is potentially null错误:不能在“FormState”上调用方法“保存”?因为它可能为空
【发布时间】:2021-08-06 03:13:17
【问题描述】:

Flutter 表单保存错误 有一个formKey,但我仍然收到错误

这是我的代码

class _TextFormFieldsState extends State<TextFormFields> {
  String _name = "";

  final formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: Theme.of(context).copyWith(    
          primaryColor: Colors.red,
          accentColor: Colors.purpleAccent,
          errorColor: Colors.black
      ),
      child: Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: Icon(Icons.save),
        ),
        appBar: AppBar(
          title: Text("Text Form Field"),
        ),
        body: Padding(
          padding: EdgeInsets.all(20),
          child: Form(
            key: formKey,
            autovalidateMode: AutovalidateMode.always,
            child: ListView(
              children: [
                TextFormField(
                  decoration: InputDecoration(
                    prefixIcon: Icon(Icons.account_circle),
                    hintText: "Your Name",
                    labelText: "FullName",
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                    ),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter some text';
                    }
                    return null;
                  },
                  onSaved: (String? value) {
                    _name = value.toString();
                  },
                ),
                ElevatedButton(
                  onPressed: () {
                    // Validate returns true if the form is valid, or false otherwise.
                    if (formKey.currentState!.validate()) {
                      formKey.currentState.save();
                      debugPrint("Girilen ad $_name");
                    }
                  },
                  child: Text('Submit'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter flutter-form-builder flutter-textinputfield


    【解决方案1】:

    这是由于Dartflow analysis

    您的formKey是一个实例变量,因此即使在您的if检查之后,也无法通过流分析检测到它绝对不是null

    改为这样使用formKey.currentState!.save();

    【讨论】:

    • 谢谢。我使用了当前状态!问题解决了。
    • 很高兴能帮上忙。 :)
    猜你喜欢
    • 1970-01-01
    • 2022-06-25
    • 2021-12-30
    • 2022-11-12
    • 1970-01-01
    • 2022-10-02
    • 1970-01-01
    • 2016-11-26
    • 2021-12-17
    相关资源
    最近更新 更多