首页 > 解决方案 > 创建动态下拉列表 - 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,
}

标签: flutterdartflutter-layout

解决方案


因为您正在检索 json 对象 ( Map) 而不是 json 列表 ( List),所以forEach必须遍历keyvalue配对,如下所示:

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(),
    )));

推荐阅读