引數型別“void Function(String)”不能分配給引數型別“void Function(String?)?”.dartargument_type_not_assignable String newValue。嗨,我在嘗試在 flutter 中實作下拉串列選單時遇到了上述錯誤
下面是我的代碼。拜托,我是顫振的新手
class _CreateAccountState extends State<CreateAccount> {
String dropdownvalue = 'Apple';
var items = ['Apple','Banana','Grapes','Orange','watermelon','Pineapple'];
@override
Widget build(BuildContext context) {
double h = MediaQuery.of(context).size.height;
double w = MediaQuery.of(context).size.width;
return Scaffold( ....
child: DropdownButton(
value: dropdownvalue,
icon: Icon(Icons.keyboard_arrow_down),
items:items.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items)
);
}
).toList(),
onChanged: (String newValue){
setState(() {
dropdownvalue = newValue;
});
},
),
謝謝你們。
uj5u.com熱心網友回復:
像這樣的錯誤與空安全相關,您可以在此處了解有關空安全的更多資訊。
如果您查看官方檔案中的DropdownButton類,您可以看到使用onChanged屬性的示例:
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
});
},
如果您簽出onChanged屬性實作:
final ValueChanged<T?>? onChanged;
這T?意味著它需要一個可以為空的型別,String?而不是一個不可為空的型別,比如String。
uj5u.com熱心網友回復:
onChanged的引數型別是void Function(String?). 所以你不能分配引數型別的函式void Function(String)
因此,請更改代碼如下:
(將String型別更改為String?“ onChanged ”引數
class _CreateAccountState extends State<CreateAccount> {
String dropdownvalue = 'Apple';
var items = ['Apple','Banana','Grapes','Orange','watermelon','Pineapple'];
@override
Widget build(BuildContext context) {
double h = MediaQuery.of(context).size.height;
double w = MediaQuery.of(context).size.width;
return Scaffold( ....
child: DropdownButton(
value: dropdownvalue,
icon: Icon(Icons.keyboard_arrow_down),
items:items.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items)
);
}
).toList(),
onChanged: (String? newValue){
setState(() {
dropdownvalue = newValue;
});
},
),
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/371750.html
