Reputation: 303
The Data Will be like this
[{ID: 1, Code: 01, Description: REGION I (ILOCOS REGION), PSGCCode: 010000000}, {ID: 2, Code: 02, Description: REGION II (CAGAYAN VALLEY), PSGCCode: 020000000},
and I only want to use the Description as the text in the DropDownButton
EDIT****
Does the Class looks like this?
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']
);
}
}
EDIT** Tried To Use or Do the Class above and Assign it to a List
List<Region> _region = [];
and Use it for my 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(),
And an Exception is Caught every time itried to tap 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)
Upvotes: 1
Views: 28128
Reputation: 2671
Short Example
// 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(),
);
}
Full example
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;
}
}
Upvotes: 1
Reputation: 777
Sample code for set dropdown from 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(),
);
}
}
}
Upvotes: 0
Reputation: 16319
If we assume your source data is properly formatted JSON, then the items
property for your DropdownButton
would look something like:
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'])),
Depending on your use case and where else you use the data, but it might help to have a class that represents your data items, then you can use map()
on json
(from the above example) to create a list of that data structure, then map from those values to the items
of the DropdownMenuItem
.
Here's a full working example:
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']);
}
}
Upvotes: 8