在迁移到空安全后,我开始在 DropdownButton
中看到此错误。
DropdownButton<String>(
value: myValue,
onChanged: (String string) { // Error
print(string);
},
items: [
DropdownMenuItem(
value: 'foo',
child: Text('Foo'),
),
DropdownMenuItem(
value: 'bar',
child: Text('Bar'),
),
],
)
错误:
<块引用>无法将参数类型“void Function(String)”分配给参数类型“void Function(String?)?”。
答案 0 :(得分:-1)
检查 value
属性的实现,它可以为空。
final T? value;
这意味着您可以向 String?
提供 value
,如果您提供 String?
,onChanged
应该不会返回 String?
。
回答您的问题:
将 onChanged
方法的类型从 String
更改为 String?
,如下所示:
onChanged: (String? string) {
print(string);
}
或者,只需省略 String?
类型,让 Dart 为您推断。
onChanged: (string) {
print(string);
}