【问题标题】:Create Item list for DropdownButton in Flutter在 Flutter 中为 DropdownButton 创建项目列表
【发布时间】:2021-08-03 06:48:02
【问题描述】:

我又遇到了 DropdownButton 的另一个问题。

DropdownButton 未启用。我在 api.flutter.dev 中找到了这个

如果 onChanged 回调为 null 或项目列表为 null 则 下拉按钮将被禁用,即其箭头将显示 呈灰色,不会响应输入。

这是我现在的代码:

return new DropdownButton<String>(
                            hint: new Text("Select Agency"),
                            value: _currentAgency,
                            onChanged: changedDropDownAgency,
                            items: snapshot.data.docs.forEach((document) {
                              return new DropdownMenuItem<String>(
                                value: document.data()['name'],
                                child: new Text(document.data()['name']),
                              );
                            }),
                          );

void changedDropDownAgency(String selected_agency) {
    setState(() {
      _currentAgency = selected_agency;
    });
    globals.selectedAgency = selected_agency;
  }

forEach 循环运行良好,在调试模式下我可以看到文档对象中有数据。我不知道如何调试 DropdownButton 代码以查看按钮未激活的原因。任何的意见都将会有帮助。 谢谢。

【问题讨论】:

    标签: flutter flutter-dropdownbutton


    【解决方案1】:

    Iterables 上的forEach() 不返回任何值(请参阅:https://api.dart.dev/stable/2.10.5/dart-core/Iterable/forEach.html),因此items 为空并且DropdownButton 被禁用。请改用map (https://api.dart.dev/stable/2.10.5/dart-core/Iterable/map.html)。示例:

    snapshot.data.docs.map<DropdownMenuItem<String>>((document) {
        return new DropdownMenuItem<String>(
            value: document.data()['name'],
            child: new Text(document.data()['name']),
        );
    }).toList(),
    

    【讨论】:

    • 感谢您的回复。但是,当我使用您的代码时,我得到以下信息: 构建 StreamBuilder(dirty, state: _StreamBuilderBaseState>#5bb78): type 'List' is not a 'List>?' 类型的子类型
    • 我已经编辑了我的答案,请看看这是否有效。我明确地告诉飞镖 Map 的返回类型应该是什么。
    • 在构建 StreamBuilder(dirty, state: _StreamBuilderBaseState>#b9a5e) 时抛出了以下断言:应该只有一项具有 [DropdownButton] 的值:选择代理商。检测到 0 个或 2 个或多个 [DropdownMenuItem] 具有相同的值 'package:flutter/src/material/dropdown.dart':断言失败:第 855 行 pos 15:'items == null ||项目.isEmpty ||值 == 空 || items.where((DropdownMenuItem item) { return item.value == value; }).length == 1'
    • return new DropdownButton( //hint: new Text("Select Agency"), value: _currentAgency, onChanged: changedDropDownAgency, items: snapshot.data.docs .map >((document) { return new DropdownMenuItem( value: document.data()['name'], child: new Text(document.data()['name']), ); }).toList( ), );
    • _currentAgency 似乎具有 'Select Agency' 的值,而您的 DropdownMenuItems 中没有一个或两个或多个似乎具有此值。您应该改用hint 并将初始值(所以_currentAgency)设置为null。
    猜你喜欢
    • 2021-01-27
    • 2020-06-10
    • 1970-01-01
    • 2020-05-07
    • 2020-11-05
    • 1970-01-01
    • 2019-07-26
    • 2020-04-11
    • 2021-09-20
    相关资源
    最近更新 更多