数据将是这样
[{ID: 1, Code: 01, Description: REGION I (ILOCOS REGION), PSGCCode: 010000000}, {ID: 2, Code: 02, Description: REGION II (CAGAYAN VALLEY), PSGCCode: 020000000},
并且我只想使用Description作为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)
答案 0 :(得分:1)
这是完整的示例
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> {
List<GenderModel> genderModelList = [];
String selectedGender;
@override
Widget build(BuildContext context) {
genderModelList = [
GenderModel('1', "Male"),
GenderModel('2', "Female"),
GenderModel('3', "Other")
];
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButtonHideUnderline(
child: new DropdownButton<String>(
hint: new Text("Select Gender"),
value: selectedGender,
isDense: true,
onChanged: (String newValue) {
setState(() {
selectedGender = newValue;
});
print(selectedGender);
},
items: genderModelList.map((GenderModel map) {
return new DropdownMenuItem<String>(
value: map.id,
child: new Text(map.name,
style: new TextStyle(color: Colors.black)),
);
}).toList(),
),
),
],
),
),
);
}
}
class GenderModel {
String id;
String name;
@override
String toString() {
return '$id $name';
}
GenderModel(this.id, this.name);
}
答案 1 :(得分:0)
如果我们假设您的源数据使用了正确的JSON格式,那么您的items
的{{1}}属性将类似于:
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()
(来自上面的示例)创建该数据结构的列表,然后将这些值映射到json
的{{1}}。
这是一个完整的工作示例:
items
答案 2 :(得分:0)
从api下拉菜单集的示例代码
class CheckOut extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<CheckOut> {
String _mySelection;
final String url ='Your api url;
List data;
Future<String> getSWData() async {
var res = await http.get(Uri.encodeFull(url));
var resBody = json.decode(res.body);
setState(() {
data = resBody;
});
return 'Success';
}
@override
void initState() {
super.initState();
this.getSWData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
backgroundColor: Colors.transparent,
iconTheme: IconThemeData.fallback(),
title: Text('CheckOut', style: TextStyle(color: Colors.black)),
centerTitle: true,
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Align(
alignment: Alignment.topCenter,
child: Container(
alignment: Alignment.center,
height: 80.0,
width: double.infinity,
color: Colors.white,
child: Column(
children: <Widget>[
new Text(
'Select Customer Name',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0),
),
SizedBox(
height: 5.0,
),
DropDown(data),
],
),
),
),
Expanded(
child: Container(
alignment: Alignment.center,
color: Colors.white,
child: Text(
'',
textAlign: TextAlign.center,
),
),
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
margin: EdgeInsets.only(bottom:20.0,left: 10.0,right: 10.0 ),
alignment: Alignment.center,
height: 50.0,
width: double.infinity,
color: Colors.white,
child: new FlatButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
color: Color(getHexColorCode.getColorHexFromStr('#FDD148')),
onPressed: () {
},
child: new Container(
padding: const EdgeInsets.symmetric(
vertical: 20.0,
horizontal: 20.0,
),
alignment: Alignment.bottomCenter,
child: new Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
new Expanded(
child: Text(
"Place Order",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 15.0,
fontWeight: FontWeight.bold),
),
),
],
),
),
),
),
),
],
),
);
}
Widget DropDown(List data)
{
if(data!=null)
{
return DropdownButton(
items: data.map((item) {
return new DropdownMenuItem(
child: new Text(
item['Name'],
style: TextStyle(fontSize: 14.0),
),
value: item['ID'].toString(),
);
}).toList(),
hint: Text(
"Please select the Customer Name",
style: TextStyle(
color: Colors.black45,
),),
onChanged: (newVal) {
setState(() {
_mySelection = newVal;
customerid = newVal;
print('customrid:' + customerid.toString());
});
},
value: _mySelection,
);
}
else{
return new Center(
child: CircularProgressIndicator(),
);
}
}
}
答案 3 :(得分:0)
简短示例
// get data using future
void _getFieldsData() {
_getDropDownData().then((data) {
final items = jsonDecode(data).cast<Map<String, dynamic>>();
var fieldListData = items.map<FormField>((json) {
return FormField.fromJson(json);
}).toList();
// update widget
setState(() {
_fieldList = fieldListData;
});
});
}
// set widget
Widget _setDropDown() {
return DropdownButton(
items: _fieldList.map((value) {
return DropdownMenuItem(
value: value.label,
child: Text(value.label, style: TextStyle(
),),
);
}).toList(),
);
}
完整示例
class _FormState extends State<Form> {
List<FormField> _fieldList = List();
String _selectedField;
@override
void initState() {
super.initState();
_getFieldsData();
}
@override
Widget build(BuildContext context) {
return _setDropDown();
}
// api call to get data
Future<String> _getDropDownData() async {
var res = await http.get(Uri.encodeFull("http://example.com/list"));
return res.body;
}
// map data to list
void _getFieldsData() {
_getDropDownData().then((data) {
final items = jsonDecode(data).cast<Map<String, dynamic>>();
var fieldListData = items.map<FormField>((json) {
return FormField.fromJson(json);
}).toList();
_selectedField = fieldListData[0].label;
// update widget
setState(() {
_fieldList = fieldListData;
});
});
}
// set Dropdown
Widget _setDropDown() {
return DropdownButton(
items: _fieldList.map((value) {
return DropdownMenuItem(
value: value.label,
child: Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8.0),
child: Text(value.label, style: TextStyle(
),),
),
);
}).toList(),
value: _selectedField,
onChanged: (value) {
setState(() {
_selectedField = value;
});
},
);
}
}
// Model Class
class FormField {
int id;
String label;
FormField({this.id, this.label});
FormField.fromJson(Map<String, dynamic> json) {
id = json['id'];
label = json['label'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['label'] = this.label;
return data;
}
}