【问题标题】:Set default value for dropdown button in flutter在颤动中设置下拉按钮的默认值
【发布时间】:2020-01-12 03:22:12
【问题描述】:

我有一个可以正常工作的下拉按钮,但是当我尝试设置默认值时,它会失败并出现以下错误:

'package:flutter/src/material/dropdown.dart':断言失败:第 620 行 pos 15:'items == null ||项目.isEmpty ||值 == 空 || items.where((DropdownMenuItem item) => item.value == value).length == 1': 不正确。

这是我的下拉按钮:

 Widget changeWorkspace() {
return StatefulBuilder(
    builder: (BuildContext context, StateSetter setState) {
  return Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
    Padding(
      padding: EdgeInsets.all(8.0),
      child: DropdownButton<AssignedWorkspace>(
          isExpanded: true,
          hint: Text("SELECT WORKSPACE"),
          value: selectedWorkspace,
          onChanged: (dropdownValueSelected) {
            setState(() {
              selectedWorkspace = dropdownValueSelected;
            });
          },
          items: workspaces != null && workspaces.length > 0
              ? workspaces.map((AssignedWorkspace workspace) {
                  return new DropdownMenuItem<AssignedWorkspace>(
                    value: workspace,
                    child: new Text(workspace.name,
                        style: new TextStyle(color: Colors.black)),
                  );
                }).toList()
              : null),
    ),
  ]);
});

}

我尝试如下设置 selectedWorkspace onInit 的值,但失败了。

selectedWorkspace = new AssignedWorkspace(
id: userSettings.currentWorkspaceId,
name: userSettings.currentWorkspaceName);

有没有办法在下拉按钮中设置默认值?

【问题讨论】:

    标签: flutter dropdown default-value dropdownbutton


    【解决方案1】:
    import 'package:flutter/material.dart';
    
    import '../config/app_theme.dart';
    
    class DropdownWidget extends StatefulWidget {
      final String title;
      final List<String> items;
      final ValueChanged<String> itemCallBack;
      final String currentItem;
      final String hintText;
    
      DropdownWidget({
        this.title,
        this.items,
        this.itemCallBack,
        this.currentItem,
        this.hintText,
      });
    
      @override
      State<StatefulWidget> createState() => _DropdownState(currentItem);
    }
    
    class _DropdownState extends State<DropdownWidget> {
      List<DropdownMenuItem<String>> dropDownItems = [];
      String currentItem;
      AppTheme appTheme;
    
      _DropdownState(this.currentItem);
    
      @override
      void initState() {
        super.initState();
        for (String item in widget.items) {
          dropDownItems.add(DropdownMenuItem(
            value: item,
            child: Text(
              item,
              style: TextStyle(
                fontSize: 16,
              ),
            ),
          ));
        }
      }
    
      @override
      void didUpdateWidget(DropdownWidget oldWidget) {
        if (this.currentItem != widget.currentItem) {
          setState(() {
            this.currentItem = widget.currentItem;
          });
        }
        super.didUpdateWidget(oldWidget);
      }
    
      @override
      Widget build(BuildContext context) {
        appTheme = AppTheme(Theme.of(context).brightness);
    
        return Container(
          margin: EdgeInsets.symmetric(vertical: 10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(left: 6),
                child: Text(
                  widget.title,
                  style: appTheme.activityAddPageTextStyle,
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(vertical: 3, horizontal: 15),
                margin: EdgeInsets.only(top: 10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(6),
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      offset: Offset(0, 2),
                      blurRadius: 10,
                      color: Color(0x19000000),
                    ),
                  ],
                ),
                child: DropdownButtonHideUnderline(
                  child: DropdownButton(
                    icon: appTheme.activityAddPageDownArrowSVG,
                    value: currentItem,
                    isExpanded: true,
                    items: dropDownItems,
                    onChanged: (selectedItem) => setState(() {
                      currentItem = selectedItem;
                      widget.itemCallBack(currentItem);
                    }),
                    hint: Container(
                      child: Text(widget.hintText, style: appTheme.hintStyle),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      }
    }
    

    这是我的 dropDownWidget 没有优化。它有 currentItem。你可以像这样使用它:

               DropdownWidget(
                    title: kStatus,
                    items: state.customerStepInfo.statusList,
                    currentItem: status,
                    hintText: kCommonPick,
                    itemCallBack: (String status) {
                      this.status = status;
                    },
                  )
    

    【讨论】:

      【解决方案2】:

      我最初将下拉变量的值更改为 1 var _value = '1'; 因此,当下拉按钮必须显示其value 时,它会显示我已将其值设置为 1 的那个,如DropDownButton 中的items 列表中的@

      DropdownButton(
                      underline: Container(),
                      onChanged: (value) {
                        setState(() {
                          _value = value;
                        });
                      },
                      value: _value,
                      items: [
                        DropdownMenuItem(
                          value: "1",
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: <Widget>[
                              Icon(MaterialCommunityIcons.devices),
                              SizedBox(width: 10),
                              Text(
                                "Consumption",
                                style: TextStyle(
                                    fontSize: 18.0, fontWeight: FontWeight.w600),
                              ),
                            ],
                          ),
                        ),
                        DropdownMenuItem(
                          value: "2",
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: <Widget>[
                              Icon(MaterialCommunityIcons.solar_panel),
                              SizedBox(width: 10),
                              Text(
                                "Generation",
                                style: TextStyle(
                                    fontSize: 18.0, fontWeight: FontWeight.w600),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
      

      【讨论】:

      • 请您将您的问题添加到 SDK 的名称中吗?
      • 它的flutter SDK
      【解决方案3】:

      您需要在 AssignedWorkspace 类中实现“等于”。我使用了equatable 包。

      示例类 AssignedWorkspace

      class AssignedWorkspace extends Equatable {
        final String id;
        final String name;
      
        AssignedWorkspace(this.id, this.name);
         
        @override
        List<Object> get props => [id];
      }
      

      【讨论】:

      • 我不明白你为什么这样做?请解释一下
      • @Mehrdad 因为在将实例类分配为值时,您必须重载等号才能正确评估两个实例是否相等。有了这个,你不需要有另一个状态(比如投票率最高的例子中的 currentItem )。仅限 AssignedWorkspace 类的实例。
      • 这是一个很好的答案,实际上从根本上解决了问题。谢谢:)
      【解决方案4】:

      对于我来说,其中一个元素的 id 为 null,一旦添加 id 为非 null,问题就得到了修复。

      【讨论】:

      • 你能解释一下,或者举一些例子什么时候元素为空
      【解决方案5】:

      如果您只想查看初始值,您可以使用名为下拉按钮参数的提示文本并设置文本小部件。我不知道这是否是一个好习惯。

      【讨论】:

        猜你喜欢
        • 2021-12-16
        • 2020-06-07
        • 2022-01-16
        • 1970-01-01
        • 2018-02-17
        • 2019-06-01
        • 2020-12-16
        • 1970-01-01
        • 2021-03-21
        相关资源
        最近更新 更多