首页 > 解决方案 > Flutter中通过DropDownList中的DropdownMenuItem传递对象

问题描述

我想在 DropDownList 中存储一个对象(在我的情况下是 Country),以便在选择后进一步处理其附加信息。

这是我要使用的列表

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

不幸的是,我无法将此项目分配给我的 DropDownList ,因为它只接受 List 的值。

所以我尝试使用

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

对于 DropDownList 并没有真正起作用。我试图想出一种方法来利用 Items 的 child 参数,但真的可以想办法。

有什么建议吗?

标签: flutterdart

解决方案


您可以在下面复制粘贴运行完整代码
假设您的Country类具有nameflag属性第 1 步:使用第 2 步
解析 json 字符串:用于生成List<Country> countryList = countryFromJson(jsonStr);
countryList.map<DropdownMenuItem<Country>>((Country value)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),

工作演示

在此处输入图像描述

完整代码

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

推荐阅读