Dart 使用FutureBuilder时,如何根据另一个下拉列表选择更改下拉列表的项目?
我有两个下拉列表,第二个下拉列表中的项目是动态的,根据第一个选择的项目下拉列表如何做?我可以创建两个单独的下拉列表,但如何创建取决于另一个Dart 使用FutureBuilder时,如何根据另一个下拉列表选择更改下拉列表的项目?,dart,flutter,Dart,Flutter,我有两个下拉列表,第二个下拉列表中的项目是动态的,根据第一个选择的项目下拉列表如何做?我可以创建两个单独的下拉列表,但如何创建取决于另一个 FutureBuilder(future: getCities(),builder: (BuildContext context, AsyncSnapshot<Post> snapshot) { return DropdownButton<String>(
FutureBuilder(future: getCities(),builder: (BuildContext context, AsyncSnapshot<Post> snapshot) {
return DropdownButton<String>(
hint: new Text(city),
items: cities.map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (String value) {
setState(() => city = value);
setState(() => getAreas(2));
},
);
}),
FutureBuilder(future: What to write here ?????,builder: (BuildContext context, AsyncSnapshot<Post> snapshot) {
return DropdownButton<String>(
hint: new Text(area),
items: areas.map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (String value) {
setState(() => area = value);
},
);
})
我认为您没有正确使用FutureBuilder小部件。您不应该在FutureBuilder声明中直接调用getCities方法,而应该在生成器中使用快照引用。下面的代码将位于您使用此FutureBuilders的state类中:
// I see that you have the AsyncSnapshot be of type Post... is there where you get // the cities list or how exactly you initialize cities list?
Future citiesFuture; // the cities future
Future areasFuture; // the data for the second drop down
// get the Future for the cities
@override void initState() {
super.initState();
citiesFuture = getCities();
}
那么您的第一个FutureBuilder将是:
FutureBuilder(future: citiesFuture, builder: (BuildContext context, AsyncSnapshot<Post> snapshot) {
// here you would initialize the cities list
List cities = snapshot.hasData ? snapshot.data : [];
return DropdownButton<String>(
hint: new Text(city),
items: cities.map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (String value) {
setState(() {
areasFuture = getAreas(2))
});
},
);
}),
您应该使用对此方法的方法调用替换第二个FutureBuilder:
Widget provideSecondDropdown() {
if (areasFuture == null) {
// the user didn't select anything from the first dropdown so you probably want to show a disabled dropdown
return DropdownButton<String>(
items: [],
onChanged:null,
}
// return the FutureBuilder based on what the user selected
return FutureBuilder(future: areasFuture, builder: (BuildContext context, AsyncSnapshot<Post> snapshot) {
List areas = snapshot.hasData ? snapshot.data : []
return DropdownButton<String>(
hint: new Text(area),
items: areas.map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (String value) {
setState(() => area = value);
},
);
})
}
第二个下拉列表中的项目将立即可用,或者您需要根据第一个下拉列表中的选择从某处获取它们?我的问题是我有一个字符串列表,该列表最初为空,将填充字符串,并且是动态的。我希望更改反映在下拉列表中