【问题标题】:The argument type 'void Function(String)' can't be assigned to the parameter type 'void Function(String?)?'参数类型“void Function(String)”不能分配给参数类型“void Function(String?)?”
【发布时间】:2021-10-22 00:47:12
【问题描述】:
Widget _buildDropDownButton(String currencyCategory) {
return DropdownButton(
  value: currencyCategory,
  items: currencies
      .map((String value) => DropdownMenuItem(
    value: value,
    child: Row(
      children: <Widget>[
        Text(value),
      ],
    ),
  ))
      .toList(),
  onChanged: (String value) {
    if(currencyCategory == fromCurrency){
      _onFromChanged(value);
    }else {
      _onToChanged(value);
    }
  },
);

}

您好,我在这部分示例代码中有一个问题,在这部分代码中:

      onChanged: (String value) {
    if(currencyCategory == fromCurrency){
      _onFromChanged(value);
    }else {
      _onToChanged(value);
    }
  },

显示错误The argument type 'void Function(String)' can't be assigned to the parameter type 'void Function(String?)?'

我尝试放置 final void Function() onChanged;final VoidCallback onChanged; 但它需要和标识符。有什么我错过的吗?

【问题讨论】:

  • 分配给onChanged 的方法需要将String? 作为参数,因为参数可以是null。错误消息告诉您提供的方法具有void Function(String) 的签名,但它需要一个具有void Function(String?) 签名的方法。

标签: flutter dart


【解决方案1】:

这是因为 null 安全性,当没有选择任何内容时,下拉列表的值可以为 null。添加一个“?”在 String 类型声明之后就像 onChanged(String? value) {//on change logic}.

查看颤振 DropdownButton 示例。

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    相关资源
    最近更新 更多