【问题标题】:How to add json list items to dropdown search items in Flutter | Dart如何在 Flutter 中将 json 列表项添加到下拉搜索项中 |镖
【发布时间】:2021-12-30 06:40:20
【问题描述】:

我正在创建一个带有搜索功能的下拉按钮。所以我使用 this package 。这个包我有问题。 API 的响应是这样的。

List countries = [
    {
      'id': '1',
      'name': 'Brazil',
    },
    {
      'id': '2',
      'name': 'India',
    },
    {
      'id': '3',
      'name': 'Japan',
    },
    {
      'id': '4',
      'name': 'Tokyo',
    },
    {
      'id': '5',
      'name': 'Australia',
    },
    {
      'id': '6',
      'name': 'Srilanka',
    },
    {
      'id': '7',
      'name': 'Canada',
    },
  ];

我的下拉代码是这样的,

body: Column(
        children: [
          DropdownSearch<String>(
            mode: Mode.MENU,
            items: countries['name'],
            showSearchBox: true,
            label: "Menu mode",
            hint: "country in menu mode",
            onChanged: (value){
               print(countries['name']);
            },
            selectedItem: "Canada",
          ),
        ],
      ),

这里items: countries['name'] 行我收到错误The argument type 'String' can't be assigned to the parameter type 'int'. 另外,当我选择一个国家时,我想打印国家ID。例如:如果我选择国家作为日本,那么它应该在控制台中打印 4。我的代码不起作用。

【问题讨论】:

    标签: flutter dart flutter-layout flutter-dependencies flutter-web


    【解决方案1】:

    首先,地图列表不能这样工作 -> (countries['name]),尝试将您的 items 替换为:

    DropdownSearch<String>(
            mode: Mode.MENU,
            items: countries.map((e)=>e['name']).toList(),
            showSearchBox: true,
            label: "Menu mode",
            hint: "country in menu mode",
            onChanged: (value){
               print(value);
            },
            selectedItem: "Canada",
          ),
    

    【讨论】:

    • 这行得通,但现在我怎样才能获得所选国家的 id。当我选择一个国家时,我想打印这个国家的 id。
    • 尝试打印(countries.singleWhere((e)=>e['name']==value)['id']);
    【解决方案2】:

    试试下面的代码希望对你有帮助。

    请参考我的回答 here 将 json 数据放到下拉菜单中

         Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: DropdownSearch<dynamic>(
                    mode: Mode.MENU,
                    items: countries.map((e) => e['name']).toList(),
                    showSearchBox: true,
                    label: "Menu mode",
                    hint: "country in menu mode",
                    onChanged: (value) {},
                    selectedItem: "Canada",
                  ),
                ),
    

    您的结果屏幕->

    【讨论】:

    • 当我选择它时,我想在控制台中打印国家的 id。我怎样才能做到这一点。我在 onChanged 函数中添加的内容以获取此 ID。
    猜你喜欢
    • 2022-12-19
    • 2019-04-27
    • 2017-01-18
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 2022-12-29
    相关资源
    最近更新 更多