简体   繁体   English

如何使用 JSON 数据列表创建 DropdownButton,我希望它在 Flutter 中填充我的 DropDownButton

[英]How to Create DropdownButton with a list of JSON Data and I want it to populate my DropDownButton in Flutter

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我只想使用描述作为 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并将其用于我的 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每次尝试点击 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)

If we assume your source data is properly formatted JSON, then the items property for your DropdownButton would look something like:如果我们假设您的源数据格式正确,则您的DropdownButtonitems属性将如下所示:

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 .根据您的用例以及您在何处使用数据,但拥有一个代表您的数据项的类可能会有所帮助,然后您可以在json上使用map() (来自上面的示例)来创建该数据结构的列表,然后从这些值映射到DropdownMenuItemitems

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']);
  }
}

Here is the full example这是完整的例子

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

}

在此处输入图片说明

Sample code for set dropdown from api从 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(),
        );
        }
      }

    }

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


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM