首页 > 解决方案 > 如何使用 JSON 数据列表创建 DropdownButton,我希望它在 Flutter 中填充我的 DropDownButton

问题描述

数据会是这样的

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

标签: dartflutter

解决方案


如果我们假设您的源数据是格式正确的 JSON,那么items您的属性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()on json(来自上面的示例)创建该数据结构的列表,然后从的那些值itemsDropdownMenuItem

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

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

推荐阅读