flutter - 创建动态下拉列表 - Flutter 问题项读取为零
问题描述
您好,我尝试使用颤振创建动态下拉列表。对端点的请求成功返回数据,但 DropdownButtonFormField 项目数组读取为零。它根本没有获取数据。请问有人可以帮我吗?
下拉菜单项变量:
List<DropdownMenuItem> _anchorLists = List<DropdownMenuItem>();
dynamic _selectedAnchor;
void initState() {
super.initState();
_getAnchorsByProvider();
}
功能:
_getAnchorsByProvider() async {
try {
_prefs = await SharedPreferences.getInstance();
var _anchorService = AnchorService();
var result = await _anchorService
.getAnchorsByProviderId(_prefs.getInt('providerOid'));
var anchors = json.decode(result.body);
anchors.forEach((anchor) {
setState(() {
_anchorLists.add(DropdownMenuItem(
child: Text(anchor['acronym']),
value: anchor['oid'],
));
});
});
setState(() {
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
});
return e.toString();
}
}
下拉菜单
SizedBox(height: 20),
(_anchorLists.length > 0)?
DropdownButtonFormField(
value: _selectedAnchor,
items: _anchorLists,
hint: const Text('Select your Anchor'),
onChanged: (value) {
setState(() {
_selectedAnchor = value;
});
},
)
: Text('Loading'),
json的值:
{
"oid": 1,
"acronym": "MAAN",
"contactAddress": "Abuja",
"idCardInstruction": null,
}
解决方案
因为您正在检索 json 对象 ( Map
) 而不是 json 列表 ( List
),所以forEach
必须遍历key
和value
配对,如下所示:
anchors.forEach((key, value) {
_anchorLists.add(DropdownMenuItem(
child: Text(value.toString()),
value: value.toString(),
));
});
我不确定您的具体需求,因此请进行相应调整,但如果您只想提供特定值,您可以像这样指定:
_anchorLists.addAll([anchors['acronym'], anchors['oid']]
.map((value) => DropdownMenuItem(
child: Text(value.toString()),
value: value.toString(),
)));
推荐阅读
- apache-spark - bluedata pyspark hdfs 写入访问问题:hdfs_access_control_exception:权限被拒绝
- mysql - 如何使用带有json数据的nodejs将json数据插入mysql表
- reactjs - React reducer 必须是纯函数吗?
- java - 就快捷方式而言,有什么方法可以像 Intellij 一样使用 Eclipse?
- apache-spark - pyspark streaming how to set ConnectionPool
- excel - How to create a pivot table in VBA?
- angular - 在 Angular 中测试与后端的通信
- google-apps-script - 为什么 getYear() 为 Date(2019, 1, 1) 返回 2018?
- java - Gradle 项目不会从其他项目或 javax.persistence 中导入类
- laravel - Laravel 5.8 在数据透视表上保存一对多关系