Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Objects in Flutter through DropdownMenuItem in DropDownList

Tags:

flutter

dart

i want to store an object (in my case Country) in a DropDownList to further process its additional information after the selection.

Here is the list i want to work with

String jsonFile =
        await rootBundle.loadString('data/country_phone_codes.json');
    Iterable jsonCountryList = jsonDecode(jsonFile);
    List<DropdownMenuItem> stringCountries = jsonCountryList
        .map((dyn) => new DropdownMenuItem(
              child: Text('${dyn['flag']}   ${dyn['name']}',
                  style: textStyleForTitleMedium),
              value: dyn,
            ))
        .toList();

Unfortunately i can not assign this item to my DropDownList as it only accepts value of List .

so my attempt to use

Country _selectedValue;
....
onChanged: setState(() { _selectedValue = value; });},
....

For the DropDownList does not really work. I tried to think of a way to utilise the child parameter of the Items but can really figure a way.

Is there any suggestions ?

like image 844
Bliv_Dev Avatar asked Oct 21 '25 16:10

Bliv_Dev


1 Answers

You can copy paste run full code below
Assume your Country class has name and flag attribute
Step 1: parse json string with List<Country> countryList = countryFromJson(jsonStr);
Step 2: use countryList.map<DropdownMenuItem<Country>>((Country value) to generate DropdownMenuItem

child: DropdownButton<Country>(
           ...
              onChanged: (Country newValue) {
                setState(() {
                  _selectedValue = newValue;
                });
              },
              items:
                  countryList.map<DropdownMenuItem<Country>>((Country value) {
                return DropdownMenuItem<Country>(
                  value: value,
                  child: Text(value.name + ' ' + value.flag),

working demo

enter image description here

full code

import 'package:flutter/material.dart';
import 'dart:convert';

List<Country> countryFromJson(String str) =>
    List<Country>.from(json.decode(str).map((x) => Country.fromJson(x)));

String countryToJson(List<Country> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Country {
  String name;
  String flag;

  Country({
    this.name,
    this.flag,
  });

  factory Country.fromJson(Map<String, dynamic> json) => Country(
        name: json["name"],
        flag: json["flag"],
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "flag": flag,
      };
}

void main() => runApp(MyApp());

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: MyStatefulWidget(),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Country _selectedValue;
  static String jsonStr = '''
  [
    {"name":"a", "flag":"a1"},
    {"name":"b", "flag":"b1"},
    {"name":"c", "flag":"c1"}
    ]
  ''';
  List<Country> countryList = countryFromJson(jsonStr);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          Center(
            child: DropdownButton<Country>(
              //isDense: true,
              hint: Text('Choose'),
              value: _selectedValue,
              icon: Icon(Icons.check_circle_outline),
              iconSize: 24,
              elevation: 16,
              style: TextStyle(color: Colors.deepPurple),
              underline: Container(
                height: 2,
                color: Colors.blue[300],
              ),
              onChanged: (Country newValue) {
                setState(() {
                  _selectedValue = newValue;
                });
              },
              items:
                  countryList.map<DropdownMenuItem<Country>>((Country value) {
                return DropdownMenuItem<Country>(
                  value: value,
                  child: Text(value.name + ' ' + value.flag),
                );
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }
}
like image 189
chunhunghan Avatar answered Oct 23 '25 07:10

chunhunghan