【问题标题】:Flutter populate dropdownmenu with JSONFlutter 使用 JSON 填充下拉菜单
【发布时间】:2018-03-19 10:09:02
【问题描述】:

我正在尝试获取从 rest api 返回的 JSON 并填充下拉菜单,我需要具有与子值不同的值。有没有人这样做或有一个例子或建议。我正在使用基本示例,似乎找不到使用 JSON 代替静态列表的方法。以下是我尝试过的,但仍然找不到价值。我不断收到飞镖空错误。任何帮助都会很棒。我已经更新了如何获取 JSON 和解码。我已经尝试了几件事。这也是错误,但我已经在调试中确认该值永远不会为空,因此它必须与 JSON 相关。我尝试过使用静态列表,它可以工作。

'package:flutter/src/material/dropdown.dart': Failed assertion: line 433 pos 15: 'value == null

String _referPractice = '<New>';

JSON 看起来像这样:

[{"id":0,"name":"<New>"},{"id":1,"name":"Test Practice"}]


var http = createHttpClient();
var response = await http.get(_url);
var practices = await jsonCodec.decode(response.body);
practicelist = await practices.toList();

new DropdownButton<String>(
        value: _referPractice,
        isDense: true,
        onChanged: (String newValue) {
          setState(() {
            _referPractice = newValue;
          });
        },
        items: practicelist.map((value) {
          return new DropdownMenuItem<String>(
            value: value['id'].toString(),
            child: new Text(value['name']),
          );
        }).toList(),
      ),

【问题讨论】:

  • 你从哪里得到空错误?您是如何将 JSON 文件解码到您的应用程序中的?
  • _referPractice 最初是什么? practices 地图的结构如何?
  • 您提供的 JSON 代表代码中的哪个变量?
  • 我想要做的是使值成为 id (value: value['id'].toString()) 并且孩子成为名称的文本(child: new Text (value['name']),) 以便我稍后可以在调用中传递 id。

标签: flutter


【解决方案1】:

您收到此错误是因为您正在使用 !null 的值初始化 _referPractice,并且您将其提供给 DropDownButton 的属性 value,它表示当前选定的项目,并且必须如果尚未选择任何项目,则为 null。

我已经使用您提供的 JSON 复制了您的示例:

String _mySelection;
  List<Map> _myJson = [{"id":0,"name":"<New>"},{"id":1,"name":"Test Practice"}];

  @override
  Widget build(BuildContext context) {
     return new Scaffold(
        body: new Center(
          child: new DropdownButton<String>(
            isDense: true,
            hint: new Text("Select"),
            value: _mySelection,
            onChanged: (String newValue) {

              setState(() {
                _mySelection = newValue;
              });

              print (_mySelection);
            },
            items: _myJson.map((Map map) {
              return new DropdownMenuItem<String>(
                value: map["id"].toString(),
                child: new Text(
                  map["name"],
                ),
              );
            }).toList(),
          ),
        ),
      );

  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    相关资源
    最近更新 更多