问题描述
我正在尝试将字符串列表添加到将来的DropdwonButton中,但是它不能正常工作,我是新手。
我写了一个FutureBuilder来从API(许多国家/地区)获取数据,但效果很好,但是当我将数据添加到DropdwonButton时,它什么也没有显示,并且指示的错误是“方法调用为null”
这是我的代码:
声明:
List countries = List();
Positions pos;
Future<Positions> _posi;
未来功能:
Future<Positions> getPosition() async {
var response = await http.get('https://umrahashal.com/api/getpositions');
var obj = jsonDecode(response.body);
pos = Positions.fromJson(obj);
return pos;
}
initState:
@override
void initState() {
super.initState();
_posi = getPosition();
_dropDownMenuItemsCountries = getDropDownMenuItemsCountries();
currentCounty = _dropDownMenuItemsCountries[0].value;
}
FutureBuilder:
FutureBuilder(
future: _posi,builder: (_,AsyncSnapshot<Positions> snapshot){
switch (snapshot.connectionState) {
case ConnectionState.active:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
break;
case ConnectionState.done:
if (snapshot.hasData && !snapshot.hasError) {
if (snapshot.data == null) {
return Text("No Data",style: new TextStyle( fontSize: 20.0));
} else {
for(int i=0; i<= snapshot.data.countries.length;i++){
countries.add(snapshot.data.countries[i].name);
}
return
Padding(
padding: EdgeInsets.only(top: size.height * 00.2383,bottom: 1),child: ListView(
padding: const EdgeInsets.all(10),children: <Widget>[
Container(
height: size.height * 0.1047,decoration: Boxdecoration(
color:NeumorphicTheme.baseColor(context),borderRadius: BorderRadius.circular(29)),child: Row(
mainAxisAlignment: MainAxisAlignment.end,children: <Widget>[
new DropdownButton(
value: currentCounty,items: _dropDownMenuItemsCountries,onChanged: changedDropDownItemCountry,),SizedBox(
width: size.width * .55,Image.asset('assets/images/r3.png'),],)),SizedBox(height: size.height * 0.0369),
解决方法
您需要将这些项目声明为小部件列表,例如in
items: <String>['One','Two','Free','Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,child: Text(value),);
}).toList(),
这将创建一个列表[Text('One'),....]