我有两个下拉菜单,根据第一个选定的下拉菜单,第二个菜单项是动态的。如何做?我可以两个单独的下拉菜单,但如何制作取决于下拉菜单一个
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);
},
);
})
答案 0 :(得分:0)
我认为您使用的FutureBuilder小部件不正确。您不应直接在FutureBuilder声明中调用getCities()方法,而应在构建器中使用快照引用。下面的代码将在您使用此FutureBuilders的状态类中:
// 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);
},
);
})
}