[英]How to give dynamic no of PopupMenuItem to the PopupMenuButton with flutter?
如何将PopupMenuItem
的 no 动态设置为具有类似ListView.builder()
的索引的PopupMenuButton
。
实际上,我正在使用FutureBuilder
从 api 获取数据,作为响应,获取了 4 个项目意味着它提供了动态的项目数。 并希望以列表形式将它们显示到PopupMenuItem
中。 但与ListView.builder()
不同, PopupMenuButton
中没有计数构造函数。
代码:
FutureBuilder<CommonModel>(
future: futureListMaterialStatusCommonModel,
builder:(BuildContext context, AsyncSnapshot<CommonModel> snapshot ){
if(!snapshot.hasData){
return Text("loading...");
}
if(snapshot.hasError){
return Text(snapshot.error);
}
//I tried to get solution by loop before showing items but went wrong
for(int i ; i< snapshot.data.content.length; i++){
itemList.add(
PopupMenuItem(
value: snapshot.data.content[i].title,//919876543210,
child: Text(
snapshot.data.content[0].title,
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.w700),
),
),
);
}
return PopupMenuButton<String>(
itemBuilder: (context) => [
PopupMenuItem(
value: snapshot.data.content[0].title,
child: Text(
snapshot.data.content[0].title,
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.w700),
),
),
],
onSelected: (value) {
setState(() {
materialStatus = value;
});
},
child: materialStatus==null? Text("Select...",
style: TextStyle(color:Colors.orange),)
:Text(materialStatus,
style: TextStyle(color:Colors.black, fontWeight: FontWeight.bold),)
);
} ,
)
最后我成功了。 这太简单了,我真的太笨了。
return PopupMenuButton<String>(
itemBuilder: (context ) =>
snapshot.data.content
.map((item) => PopupMenuItem<String>(
value: item.title,
child: Text(
item.title,
),
))
.toList(),
onSelected: (value) {
setState(() {
materialStatus = value;
});
},
child: materialStatus ==null? Text("Select...",
style: TextStyle(color:Colors.orange),)
:Text(materialStatus,
style: TextStyle(color:Colors.black, fontWeight: FontWeight.bold),)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.