【问题标题】:How to add data in dropdown dynamically?如何在下拉列表中动态添加数据?
【发布时间】:2021-10-06 05:44:42
【问题描述】:

当用户在该文本框中输入一些值时,我有一个文本框,API 被调用,我从该用户输入的文本开始获取数据,我从 API 获取的数据我希望该数据添加到下拉列表中,用户可以选择来自该数据的多个值我该怎么做?

【问题讨论】:

    标签: flutter api dart


    【解决方案1】:

    您可以在此列表变量中使用小部件列表,也可以将 http 数据放入该列表变量中..

    List Mylist;
    var url = Uri.parse("your Api link here");
    
    var data = await http.get(url).then((value) {
      setState(() {
        Mylist = jsonDecode(value.body);
        
      });
    
    });DropdownButton(
        items: Mylist.map((String value) {
          return DropdownMenuItem(
          value: value,
         child: Text(value),
       );
        }).toList(),
       onChanged: (_) {},
     )
    

    【讨论】:

      【解决方案2】:

      首先,我们声明一个 Future 从 API 端点获取数据,如下所示:

        List<Widget> listForm = []; //initialized to an empty list
      
        fetchFromApui(url) async {
          List<dynamic> myList = [];
          var data = await http.get(url).then((value) {
            List response = jsonDecode(value.body);
            response.map((e) => myList.add(e));
          });
        }
      

      然后将使用 FutureBuilder 通过 DropDownButton 将数据加载到 UI:

      @override
        Widget build(BuildContext context) {
          return Scaffold(
            appBar: AppBar(
              title: Text(widget.title),
            ),
            body: FutureBuilder<List<dynamic>?>(
                future: fetchFromApui('https://theApiEndPointUrl'),
                builder: (context, snapshot) {
                  return DropdownButton(
                      items: snapshot.data!.map((e) {
                    return DropdownMenuItem(
                      child: Container(
                        child: Text(snapshot.data.toString()),
                      ),
                    );
                  }).toList());
                }),
          );
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-27
        • 1970-01-01
        • 2016-10-19
        • 1970-01-01
        • 2020-02-15
        • 2016-11-03
        • 2017-04-15
        • 2021-08-04
        相关资源
        最近更新 更多