首页 > 解决方案 > 作用域模型 - 接收者:闭包:({dynamic formData})=> void from Function 'login'

问题描述

我正在尝试实现 ScopedModel,我有这样的代码示例没有任何问题,但是当我尝试实现相同的算法时,我得到了错误。这里有你需要的东西:

登录按钮代码块:

void _submitForm(Function authenticate) async {
    _formKey.currentState.save();
    print(_formData);
    http.Response response = await authenticate(_formData);
  }

范围模型登录代码块:

void login({Map<String, dynamic> formData}) async {
    http.Response response = await http.post(
      url,
      body: formData,
    );
    print(response.body);
  }

按下代码:

onPressed: () => _submitForm(model.login),

错误:

NoSuchMethodError: Closure call with mismatched arguments: function '_MainModel&Model&ConnectedModel&AuthModel.login'
E/flutter (13496): Receiver: Closure: ({dynamic formData}) => void from Function 'login':.
E/flutter (13496): Tried calling: _MainModel&Model&ConnectedModel&AuthModel.login(_LinkedHashMap len:3)
E/flutter (13496): Found: _MainModel&Model&ConnectedModel&AuthModel.login({dynamic formData}) => void

我试图改变方法的类型等。没有任何工作正常。

我通过 Scoped Model 对不同风格的实现持开放态度。

标签: dartflutter

解决方案


该错误是因为您将一个带有参数的函数传递给一个方法,该方法需要一个不带参数的函数。

试试这个:

void _submitForm(Function(Map<String, dynamic>) authenticate) async {
  _formKey.currentState.save();
  print(_formData);
  http.Response response = await authenticate(_formData);
}

我可能错了,但我认为您不能传递包含命名参数的函数,因此您的作用域模型代码需要是:

void login(Map<String, dynamic> formData) async {
  http.Response response = await http.post(
    url,
    body: formData,
  );
  print(response.body);
}

推荐阅读