Dart 如何使用JSON数据列表创建DropdownButton,我希望它能够在Flatter中填充我的DropdownButton

Dart 如何使用JSON数据列表创建DropdownButton,我希望它能够在Flatter中填充我的DropdownButton,dart,flutter,Dart,Flutter,数据将是这样的 [{ID: 1, Code: 01, Description: REGION I (ILOCOS REGION), PSGCCode: 010000000}, {ID: 2, Code: 02, Description: REGION II (CAGAYAN VALLEY), PSGCCode: 020000000}, 我只想使用描述作为下拉按钮中的文本 编辑**** 这个班看起来像这样吗 class Region { final int regionid; fina

数据将是这样的

[{ID: 1, Code: 01, Description: REGION I (ILOCOS REGION), PSGCCode: 010000000}, {ID: 2, Code: 02, Description: REGION II (CAGAYAN VALLEY), PSGCCode: 020000000},
我只想使用描述作为下拉按钮中的文本

编辑****

这个班看起来像这样吗

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']

    );
  }
}

如果我们假设您的源数据是正确格式化的JSON,那么您的
下拉按钮的
items
属性将如下所示:

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'])),

如果我们假设您的源数据是正确格式化的JSON,那么您的
下拉按钮的
items
属性将如下所示:

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'])),

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

    }
类签出扩展了StatefulWidget{
@凌驾
_MyAppState createState()=>\u MyAppState();
}
类MyAppState扩展了状态{
字符串(u)选举;;
最后一个字符串url=”您的api url;
列出数据;
Future getSWData()异步{
var res=await http.get(Uri.encodeFull(url));
var resBody=json.decode(res.body);
设置状态(){
数据=resBody;
});
回归"成功",;
}
@凌驾
void initState(){
super.initState();
这是.getSWData();
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标高:0.0,
背景颜色:颜色。透明,
iconTheme:IconThemeData.fallback(),
标题:文本(“签出”,样式:TextStyle(颜色:Colors.black)),
标题:对,
),
正文:专栏(
crossAxisAlignment:crossAxisAlignment.stretch,
儿童:[
对齐(
对齐:alignment.topCenter,
子:容器(
对齐:对齐.center,
身高:80.0,
宽度:double.infinity,
颜色:颜色,白色,
子:列(
儿童:[
新文本(
“选择客户名称”,
样式:TextStyle(fontWeight:fontWeight.bold,fontSize:16.0),
),
大小盒子(
身高:5.0,
),
下拉列表(数据),
],
),
),
),
扩大(
子:容器(
对齐:对齐.center,
颜色:颜色,白色,
子:文本(
'',
textAlign:textAlign.center,
),
),
),
对齐(
对齐:对齐.bottomCenter,
子:容器(
边距:仅限边集(底部:20.0,左侧:10.0,右侧:10.0),
对齐:对齐.center,
身高:50.0,
宽度:double.infinity,
颜色:颜色,白色,
孩子:新的扁平按钮(
形状:新的RoundedRectangleBorder(
边界半径:新边界半径。圆形(30.0),
),
颜色:颜色(getHexColorCode.getColorHexFromStr('#FDD148')),
已按下:(){
},
子容器:新容器(
填充:const EdgeInsets.symmetric(
垂直线:20.0,
水平:20.0,
),
对齐:对齐.bottomCenter,
孩子:新的一排(
mainAxisSize:mainAxisSize.max,
mainAxisAlignment:mainAxisAlignment.end,
儿童:[
新扩展(
子:文本(
“下单”,
textAlign:textAlign.center,
样式:TextStyle(
颜色:颜色,白色,
字体大小:15.0,
fontWeight:fontWeight.bold),
),
),
],
),
),
),
),
),
],
),
);
}
小部件下拉列表(列表数据)
{
如果(数据!=null)
{
返回下拉按钮(
条目:data.map((条目){
返回新的DropdownMenuItem(
儿童:新文本(
项目['Name'],
样式:TextStyle(fontSize:14.0),
),
值:项['ID'].toString(),
);
}).toList(),
提示:文本(
“请选择客户名称”,
样式:TextStyle(
颜色:颜色。黑色45,
),),
更改后:(newVal){
设置状态(){
_mySelection=newVal;
customerid=newVal;
打印('customrid:'+customerid.toString());
});
},
值:_mySelection,
);
}
否则{
返回新中心(
子对象:CircularProgressIndicator(),
);
}
}
}

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

    }
类签出扩展了StatefulWidget{
@凌驾
_MyAppState createState()=>\u MyAppState();
}
类MyAppState扩展了状态{
字符串(u)选举;;
最后一个字符串url=”您的api url;
列出数据;
Future getSWData()异步{
var res=await http.get(Uri.encodeFull(url));
var resBody=json.decode(res.body);
设置状态(){
数据=resBody;
});
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']);
  }
}
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(),
        );
        }
      }

    }
// 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;
  }
}


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

}