【问题标题】:How to Create DropdownButton with a list of JSON Data and I want it to populate my DropDownButton in Flutter如何使用 JSON 数据列表创建 DropdownButton,我希望它在 Flutter 中填充我的 DropDownButton
【发布时间】:2018-07-27 08:30:58
【问题描述】:

数据会是这样的

[{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)

【问题讨论】:

    标签: dart flutter


    【解决方案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);
    
    }
    

    【讨论】:

      【解决方案2】:

      如果我们假设您的源数据是格式正确的 JSON,那么您的 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'])),
      

      根据您的用例以及您在哪里使用数据,但拥有一个代表您的数据项的类可能会有所帮助,然后您可以在json 上使用map()(来自上面的示例)创建一个该数据结构的列表,然后将这些值映射到DropdownMenuItemitems

      这是一个完整的工作示例:

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

      【讨论】:

      • hmm 什么样的课,比如Edit的那个?
      • 是的,您的课程和方法看起来不错。您的下拉按钮是否声明为DropdownButton&lt;String&gt;
      • 是的,每次点击它都会捕获到上面的异常
      • 我已经根据您迄今为止分享的内容,用一个完整的工作示例编辑了我的答案。鉴于例外,它可能与布局有关,那么它是什么样的?
      • 找到了那个错误的原因,顺便说一句,我应该用'${map.regionDescription}'来包装map.regionDescription,谢谢
      【解决方案3】:

      简短示例

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2020-06-10
          • 2021-08-03
          • 2021-01-27
          • 1970-01-01
          • 2021-01-18
          • 2021-01-17
          • 2019-07-26
          • 2019-07-03
          • 1970-01-01
          相关资源
          最近更新 更多