【问题标题】:DropdownButton not working as expected in FlutterDropdownButton 在 Flutter 中无法正常工作
【发布时间】:2023-01-04 22:55:23
【问题描述】:

我是 Flutter 开发的新手。正在填充从 DropdownButtonlist 中的 API 接收的快照数据。一切正常。但是当我更改列表中的项目时,出现上述错误。我不确定是哪一个导致了 pbm。我在网上冲浪了很多,但找不到解决方案。即使列表中有一项,我也会收到错误消息。我收到错误消息“错误:在 flutter 中检测到零个或 2 个或更多 [DropdownMenuItem] 具有相同的值” 提前致谢

FutureBuilder(
              future:Api.getSchemes(context),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                return snapshot.hasData
                    ? Container(
                  padding: EdgeInsets.all(5),
                    decoration: BoxDecoration(
                      color: Color(0xffF3D876),
                      borderRadius: BorderRadius.circular(10),
                    ),

                  child: DropdownButton<ClsSchemes>(
                    alignment: AlignmentDirectional.centerStart,
                    isExpanded: true,
                    value: dropDownValue,
                    hint: Text(dropDownValue.Scheme_Name ?? 'Make a selection'),
                    items: snapshot.data.map<DropdownMenuItem<ClsSchemes>>((item) {
                      return DropdownMenuItem<ClsSchemes>(

                        value: item,
                        child: Text(item.Scheme_Name),
                      );
                    }).toList(),
                    onChanged: (value) {
                      setState(() {
                        dropDownValue = value!;
                        TotalDues = value.Total_Dues;
                      });
                    },
                  ),
                )
                    : Container(
                  child: Center(
                    child: Text('Loading...'),
                  ),
                );
              },
            ),

【问题讨论】:

  • 可能 snapshot.data 包含重复项
  • 我查过了。没有重复。即使列表只有一项,也会出现错误
  • 你能包括如何清除dropDownValue

标签: flutter dart


【解决方案1】:

由于您使用 ClsSchemes 的实例作为您的值,因此您需要确保 operator == 确实适用于您的班级。

为此,您需要覆盖 == 运算符hashCode:

示例取自here

class Example {
  final int value;
  Example(this.value);

  @override
  bool operator ==(Object other) =>
      other is Example &&
      other.runtimeType == runtimeType &&
      other.value == value;

  @override
  int get hashCode => value.hashCode;
}

你需要找出你班级的识别价值是什么。这些类中的两个什么时候相等?

如果您已经有作为“身份”字段的特定字段,equatable 包会使它变得更容易一些。

【讨论】:

    猜你喜欢
    • 2021-08-22
    • 2021-05-17
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2018-09-27
    • 2021-05-28
    相关资源
    最近更新 更多