dart - 如何使用 JSON 数据列表创建 DropdownButton,我希望它在 Flutter 中填充我的 DropDownButton
问题描述
数据会是这样的
[{ID: 1, Code: 01, Description: REGION I (ILOCOS REGION), PSGCCode: 010000000}, {ID: 2, Code: 02, Description: REGION II (CAGAYAN VALLEY), PSGCCode: 020000000},
我只想将描述用作 DropDownButton 中的文本
编辑****
类看起来像这样吗?
class Region {
final int regionid;
final String regionDescription;
Region ({
this.regionid,
this.regionDescription
});
factory Region.fromJson(Map<String, dynamic> json) {
return new Region(
regionid: json['id'],
regionDescription: json['description']
);
}
}
编辑** 尝试使用或执行上述课程并将其分配给列表
List<Region> _region = [];
并将其用于我的 DropDownItems
child: new DropdownButtonHideUnderline(
child: new DropdownButton<String>(
hint: new Text("Select Region"),
value: selectedRegion,
isDense: true,
onChanged: (String newValue) {
setState(() {
selectedRegion = newValue;
});
print(selectedRegion);
},
items: _region.map((Region map) {
return new DropdownMenuItem<String>(
value: map.regionDescription,
child: new Text(map.regionDescription,
style: new TextStyle(color: Colors.black)),
);
}).toList(),
每次尝试点击 DropdownButton 时都会捕获一个异常
I/flutter (11272): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (11272): The following ArgumentError was thrown during paint():
I/flutter (11272): Invalid argument(s): 0.0
I/flutter (11272): When the exception was thrown, this was the stack:
I/flutter (11272): #0 double.clamp (dart:core/runtime/libdouble.dart:143:7)
I/flutter (11272): #1 _DropdownMenuPainter.paint (package:flutter/src/material/dropdown.dart:57:33)
I/flutter (11272): #2 RenderCustomPaint._paintWithPainter (package:flutter/src/rendering/custom_paint.dart:520:13)
I/flutter (11272): #3 RenderCustomPaint.paint (package:flutter/src/rendering/custom_paint.dart:558:7)
I/flutter (11272): #4 RenderObject._paintWithContext (package:flutter/src/rendering/object.dart:2018:7)
I/flutter (11272): #5 PaintingContext.paintChild (package:flutter/src/rendering/object.dart:130:13)
解决方案
如果我们假设您的源数据是格式正确的 JSON,那么items
您的属性DropdownButton
将类似于:
import 'dart:convert';
var data = '[{"ID":"1", ...';
var json = JsonDecoder().convert(data);
// …
items: json.map<String>((item) => DropdownMenuItem<String>(
value: item['Description'],
child: Text(item['Description'])),
根据您的用例以及您使用数据的其他位置,但拥有一个表示您的数据项的类可能会有所帮助,然后您可以使用map()
on json
(来自上面的示例)创建该数据结构的列表,然后从的那些值items
。DropdownMenuItem
这是一个完整的工作示例:
import 'dart:convert';
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final String data =
'[{"ID": 1, "Code": "01", "Description": "REGION I (ILOCOS REGION)", "PSGCCode": "010000000"}, {"ID": 2, "Code": "02", "Description": "REGION II (CAGAYAN VALLEY)", "PSGCCode": "020000000"}]';
List<Region> _region = [];
String selectedRegion;
@override
Widget build(BuildContext context) {
final json = JsonDecoder().convert(data);
_region = (json).map<Region>((item) => Region.fromJson(item)).toList();
selectedRegion = _region[0].regionDescription;
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButtonHideUnderline(
child: new DropdownButton<String>(
hint: new Text("Select Region"),
value: selectedRegion,
isDense: true,
onChanged: (String newValue) {
setState(() {
selectedRegion = newValue;
});
print(selectedRegion);
},
items: _region.map((Region map) {
return new DropdownMenuItem<String>(
value: map.regionDescription,
child: new Text(map.regionDescription,
style: new TextStyle(color: Colors.black)),
);
}).toList(),
),
),
],
),
),
);
}
}
class Region {
final int regionid;
final String regionDescription;
Region({this.regionid, this.regionDescription});
factory Region.fromJson(Map<String, dynamic> json) {
return new Region(
regionid: json['ID'], regionDescription: json['Description']);
}
}
推荐阅读
- ruby-on-rails - 在 Ruby on Rails 中使用 IP 代理
- reactjs - how to use React Redux to display data without mapping method
- python - 使用两个变量在 Flask 中更新 MySQL 数据库
- javascript - 如何在类构造函数中记录对象?
- excel - How to Return a Comma Separated Value List to single Excel Cell based on Condition from Range
- expression - 在 Qlik Sense 中为变量值添加书签
- javascript - 如何限制画线的位置
- macos - 我可以在磁盘映像打开时修改它,但不能“保存更改”吗?
- c++ - How do some libraries override operator[] with multiple return types?
- vue.js - How to save category in laravel 5.7 with vue.js