在 Flutter 中为 DropdownButton 创建项目列表

Create Item list for DropdownButton in Flutter

我回来时遇到了 DropdownButton 的另一个问题。

DropdownButton 未启用。我在 api.flutter.dev

中找到了这个

If the onChanged callback is null or the list of items is null then the dropdown button will be disabled, i.e. its arrow will be displayed in grey and it will not respond to input.

这是我的代码:

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 代码以查看按钮未激活的原因。任何的意见都将会有帮助。 谢谢

Iterables 上的

forEach() 没有 return 任何值(参见:https://api.dart.dev/stable/2.10.5/dart-core/Iterable/forEach.html), and thus items is null and the DropdownButton is disabled. Use map instead (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(),