flutter - 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 参数,但真的可以想办法。
有什么建议吗?
解决方案
您可以在下面复制粘贴运行完整代码
假设您的Country
类具有name
和flag
属性第 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(),
),
),
],
),
);
}
}
推荐阅读
- istio - 具有标头和 url 匹配的 Istio VirtualService 规则
- javascript - 移动键盘覆盖的 Html 输入文本 (Android - Ios)
- python - 如何在追加时将字典的顺序更新为最后
- swiftui - SwiftUI - ScrollView 移动所选项目
- mongodb - 集合A有一个外国人和B,B有一个外国人和集合C,我怎样才能把一个外国人从A带到集合C?(汇总)
- redux - Redux:我可以在减速器中改变状态并传递相同的新对象吗
- python - 如何替换df列中的部分字符串
- python - 在 Word 中打开时使用 Python 编辑 word (.docx) 文件
- reactjs - 无法在formik中使用useField上传文件
- c++ - C++模板类中的段错误