Ad

How To Add Json List Items To Dropdown Search Items In Flutter | Dart

I'm creating a dropdown button with search. So I using this package . Here with this package I have problem. The response from the API is like this.

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',
    },
  ];

My Dropdown code is this,

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",
          ),
        ],
      ),

Here items: countries['name'] line i getting error as The argument type 'String' can't be assigned to the parameter type 'int'. Also when i select a country i want to print the country id. eg: if i select country as japan then it should print 4 in console. My Code is not working.

Ad

Answer

First of all, a List of Map doesn't work like this -> (countries['name]), try replace your items to:

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",
      ),
Ad
source: stackoverflow.com
Ad