我已經解決了其他類似的問題,但沒有一個對我有用。
當我在 Dropdown 中選擇值時,會呼叫 setState 方法并將新值存盤在 dropdownValue 變數中。但這種變化并沒有反映在螢屏上。
class _ComparisonScreenState extends State<ComparisonScreen> {
Widget titleWidget = const Text('Loading...'); //Initial widget which gets replaced by a drowpdown menu after async call to the DB returns values.
String dropdownValue = 'Contradiction 1'; //holds the initial value in the dropdown.
@override
void initState() {
databaseObject.getContradictions().then( //async call to the DB to fetch data.
(contradictions) { //stores the list of contradictions
setState(
() {
titleWidget = DropdownButton<String>(
isExpanded: true,
// isDense: true,
items: contradictions.header.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: ListTile(
title: Text(value),
subtitle: (Text(value)),
),
);
}).toList(),
value: dropdownValue,
icon: const Icon(Icons.arrow_downward),
iconSize: 24,
style: const TextStyle(color: Colors.white),
underline: Container(
height: 2,
color: Colors.white70,
),
onChanged: (String? newValue) {
setState(
() {
dropdownValue = newValue!;
},
);
},
);
},
);
},
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: const CommonDrawer(currentScreen: 'ComparisonScreen'),
appBar: AppBar(
actions: const [
Padding(
padding: EdgeInsets.only(right: 20),
child: Icon(Icons.settings),
),
],
title: titleWidget,
),
body: Container(),
);
}
}
謝謝你
uj5u.com熱心網友回復:
當您呼叫setState()框架時,會安排一個新的構建呼叫并重新創建小部件子樹。然后框架將新的小部件子樹與先前的小部件子樹進行比較,以查看是否有任何更改。由于titleWidget從下拉串列中選擇值后不會重新創建物件dropdownValue,因此titleWidget. 簡而言之,這意味著您必須創建小部件物件的新實體以反映它們在構建呼叫期間的更改。框架提供了一個小部件FutureBuilder,您可以使用它來異步構建小部件。
FutureBuilder(
future: databaseObject.getContradictions,
builder: (context, snapshot) {
if (snapshot.hasData) {
final contradictions = snapshot.data;
return your_title_widget_here;
}
return your_loading_widget_here;
}
)
uj5u.com熱心網友回復:
我做了什么,我使用了一種方法并傳遞了值
void changedData(String? value){
dropdownValue = value!;
}
然后在 onChanged
onChanged: (String? newValue) {
setState(
() {
changedData(newValue!)
},
);
},
我不確定,但你可以這樣嘗試。
uj5u.com熱心網友回復:
我認為這是因為您的 DropdownButton 在initState(). 如果我沒有錯,SetState 將重建build而不是重建initState(),嘗試將 DropdownButton 放入 中build,并在 中為 DropdownButton 初始化您的專案initState()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338163.html
下一篇:如何更改日歷的語言環境?
