[英]DropdownButton is not changing the value on onChanged
在從下拉列表中進行另一次選擇后,DropdownButton不會更改下拉列表的值。 以下是我的代碼。
Flexible(
child: Padding(
padding: EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: DropdownButton(
hint: Text('Select'),
items: list_dropdown,
onChanged: (val) {
setState(() {
wd = val;
});
},
value: wd,
)),
)
在initState中我設置了value變量
@override
void initState() {
// TODO: implement initState
super.initState();
wd = 0;
}
而我在全球范圍內創建變量
int wd;
我哪里錯了?
為什么要在全局范圍內創建變量? 如果你想用setState()
改變名為wd
的變量,你必須把它放在你的狀態類中。
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
// Here wd in my state class
int wd = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Cat Attack"),
),
body: Center(
child: DropdownButton(
value: wd,
onChanged: (val) {
setState(() {
wd = val;
});
},
items: [
DropdownMenuItem(
child: Text('1'),
value: 1,
),
DropdownMenuItem(
child: Text('2'),
value: 2,
),
],
),
));
}
}
一旦定義了狀態,就可以覆蓋initState()
的wd值。
class _AppState extends State<App> {
int wd;
@override
void initState() {
super.initState();
wd = 2;
}
請記住,DropdownButton的“值”應設置為“null”,或者是值列表中的值。 因此,如果您將其設置為5,而不是1,2或null,這是我的DropdownMenuItem
中的值,您將收到此錯誤:
I / flutter(15227):══╡WIDGETS LIBRARY的例外情況╞═══════════════════════════════════════════════════════════════════════════════════════════════════ ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════>> / flutter(15227):'package:flutter / src / material / dropdown.dart':斷言失敗:第560行pos 15:'items == null || I / flutter(15227):items.isEmpty || value == null || items.where((DropdownMenuItem item)=> item.value == I / flutter(15227):value)。length == 1':不是真的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.