在颤振中为下拉按钮设置默认值

Set default value for dropdown button in flutter

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

'package:flutter/src/material/dropdown.dart': Failed assertion: line 620 pos 15: 'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem item) => item.value == value).length == 1': is not true.

这是我的下拉按钮:

 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);

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

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;
                },
              )

我最初将下拉变量的值更改为 1 var _value = '1'; 因此,当下拉按钮必须显示其 value 时,它会显示我在 DropDownButton

中的 items 列表中将其值设置为 1 的按钮
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),
                        ),
                      ],
                    ),
                  ),
                ],
              ),

您需要在 class AssignedWorkspace 中实现“equals”。我使用了 equatable 包。

示例class分配的工作空间

class AssignedWorkspace extends Equatable {
  final String id;
  final String name;

  AssignedWorkspace(this.id, this.name);
   
  @override
  List<Object> get props => [id];
}

对我来说,其中一个元素的 id 为空,一旦添加的 id 变为非空问题就得到解决。

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