【问题标题】:Error: The method can not be called because the receiver can be null [duplicate]错误:无法调用该方法,因为接收者可以为空[重复]
【发布时间】:2021-10-03 03:11:24
【问题描述】:

我试图在单击按钮时保存表单,但它给了我一个错误,“无法调用方法,因为接收器可以为空”。我提供了一个空检查,但错误没有得到解决。任何帮助将不胜感激。

这里是代码

onPressed: () {
    if (_formKey.currentState != null) {
        _formKey.currentState.save(); // this gives the error
    }
},

这个 onPressed 与提升的按钮链接,这里的 _formKey 是这样的:

// key to work with the form
final _formKey = GlobalKey<FormState>();

【问题讨论】:

    标签: android flutter dart


    【解决方案1】:

    由于您正在检查currentState 不为空,您可以使用! 来解决您的问题。

    onPressed: () {
        if (_formKey.currentState != null) {
            _formKey.currentState!.save();
        }
    },
    

    解决此问题的另一种方法是创建一个存储currentState 的变量。

    onPressed: () {
        final state = _formKey.currentState;
        if (state != null) {
            state.save();
        }
    },
    

    【讨论】:

      猜你喜欢
      • 2021-09-05
      • 2021-08-10
      • 1970-01-01
      • 2021-11-21
      • 2021-08-27
      • 2023-03-05
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      相关资源
      最近更新 更多