【问题标题】:flutter: There should be exactly one item with [DropdownButton]'s value: A. Either zero or 2 or more [DropdownMenuItem]s were detected with the sameflutter:应该只有一个项目具有 [DropdownButton] 的值:A。检测到零个或 2 个或更多 [DropdownMenuItem] 具有相同的值
【发布时间】:2023-01-26 18:10:17
【问题描述】:

我用 Flutter 制作了 DropdownButton,但出现错误“There should be exactly a item with [DropdownButton]'s value: A. 检测到具有相同值的零个或两个或多个 [DropdownMenuItem] '包:flutter/src/material/dropdown.dart': 断言失败:第 890 行第 15 行:'items == null ||项目.isEmpty ||价值==空|| items.where((DropdownMenuItem 项目) { 返回 item.value == 值; }).length == 1'"
这是代码

class HomeController extends GetxController {
 List<String> sections = [
    'A',' B',' C', ' D',' E',' F',' G'];
  String selectedLetter = "A";

  void setSectionLetter(String s) {
    selectedLetter = s;
    update();
  }
}
GetBuilder<HomeController>(builder: (contH) {
              return DropdownButton<String?>(
                items: contH.sections
                    .map((e) => DropdownMenuItem<String?>(
                        child: HDW().title(context: context, text: e)))
                    .toList(),
                value: contH.selectedLetter.isNotEmpty
                    ? contH.selectedLetter
                    : null,
                onChanged: (value) {
                  contH.setSectionLetter(value!);
                },
                isExpanded: true,
                icon: const Icon(Icons.keyboard_arrow_down),
              );
            })

请注意,我使用的是 Getx,我以前没有遇到过这个问题。

【问题讨论】:

    标签: flutter dart flutter-getx dropdownbutton flutter-dropdownbutton


    【解决方案1】:

    如果 contH.selectedLetter.isNotEmptyfalse,则 value 设置为 null。但是,sections 不包含选项 null。这解释了错误:检测到值为 null 的零个 [DropdownMenuItem]。将 null 添加到部分或将 null 更改为 sections 中已有的值。

    编辑:我试图为此制作一个 DartPad 示例,发现实际问题是您没有将值传递给 DropdownMenuItems。除了一个习惯的孩子代表一个值,还有一个 value 参数存储该选项的实际值。请参阅此 DartPad 中的第 44 行: https://dartpad.dev/?id=57eb35e737ca1420aca6a833b8bb716f

    您可以在代码中使用完全相同的行。

    【讨论】:

    • 即使我写了```值:contH.selectedLetter,```仍然是同样的问题
    • 你能告诉我代码应该是怎样的吗?
    • 用正确的答案更新它:)
    • 没有用,试了很多次,这是第一次使用 Getx 的下拉菜单,我认为问题出在那里。
    • 在 dartpad 中,您使用了没有 Getx 的普通下拉菜单
    猜你喜欢
    • 1970-01-01
    • 2023-02-16
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2020-06-16
    • 2020-07-18
    • 2023-01-05
    相关资源
    最近更新 更多