【问题标题】:"There should be exactly one item with [DropdownButton]'s value: Item1" error when using dropdownbutton in flutter在 flutter 中使用 dropdownbutton 时,“应该只有一个项目具有 [DropdownButton] 的值:Item1”错误
【发布时间】:2023-01-05 19:41:37
【问题描述】:

我正在尝试在我的 flutter 应用程序中使用下拉菜单,但出现错误。

这是代码:

List<String> items = ["Item1", "Item2", "Item3", "Item4"];
String selectedItem = "Item1";
DropdownButton<String>(
  items: items.map(
    (txt) {
      return DropdownMenuItem<String>(
        child: Text(
          "$txt"
        ),
      );
    }
  ).toList(),
  value: selectedItem,
)

在某些问题中,我看到我们必须首先将变量设置为列表中存在的值。我已经完全做到了,但仍然出现错误。

错误信息:

There should be exactly one item with [DropdownButton]'s value: Item1. 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 850 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1'

这里的错误是什么?

如果需要更多信息,请发表评论。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    这里举个例子,代码中的解释:

    class _MyHomePageState extends State<MyHomePage> {
    
      List<String> items = ["Item1", "Item2", "Item3", "Item4"];
      String selectedItem = "Item1";
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: Column(
            children: [
    
              Flex(direction: Axis.vertical, children:[
                DropdownButton<String>(
                  value: selectedItem,
                  onChanged: (_value) {  // update the selectedItem value
                    setState(() {
                      selectedItem = _value!;
                    });
                  },
                  items: items
                      .map<DropdownMenuItem<String>>((String _value) => DropdownMenuItem<String>(
                      value: _value, // add this property an pass the _value to it
                      child: Text(_value,)
                  )).toList(),
                ),
              ])
    
            ],
          ),
    
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      如果您从返回列表的 api 加载列表,请查看我为调试错误所做的工作。

      1. 创建了一个可重用的小部件来处理未来的响应

         Widget rangeLists(selectedValue) {
         return FutureBuilder(
             future: YourFuture,//this should return Future<List>
             builder: (context, snapshot) {
               if (!snapshot.hasData) {
                 return Text('Loading...');
               } else {
                 List<DropdownMenuItem<String>> categoriesItems = [
                   DropdownMenuItem(
                     child: Text(selectedValue),
                     value: selectedValue,
                   ),
                 ];
                 print('categoriesItems.last.value');
                 print(categoriesItems.last.value);
                 var snapshotAsMap = snapshot.data as List;
                 for (int i = 0; i < snapshotAsMap.length; i++) {
                   if (snapshotAsMap[i]['category'] != selectedValue) {
                     categoriesItems.add(
                       DropdownMenuItem(
                         child: Text(snapshotAsMap[i]['category']),
                         value: snapshotAsMap[i]['category'],
                       ),
                     );
                   }
                 }
                 return Padding(
                   padding: const EdgeInsets.only(left: 18.0, right: 18, top: 10),
                   child: Container(
                     padding: EdgeInsets.only(left: 25, right: 25),
                     decoration: BoxDecoration(
                         border: Border.all(color: Colors.grey, width: 1),
                         borderRadius: BorderRadius.circular(25)),
                     child: DropdownButton<String>(
                       items: categoriesItems,
                       icon: const Icon(
                         Icons.expand_more,
                         color: Colors.grey,
                       ),
                       iconSize: 24,
                       elevation: 16,
                       isExpanded: true,
                       style: const TextStyle(color: Colors.grey),
                       underline: SizedBox(),
                       onChanged: (value) {
                         setState(() {
                           widget.selectedValue = value;
                         });
                       },
                       value: selectedValue,
                       hint: Text('My courses'),
                     ),
                   ),
                 );
               }
             })};
        

        2.用法 你可以这样称呼它

        String selectedValue="Select Here"
        
        rangeLists(selectedValue)//call this as a widget in ur ui
        

        它将处理来自后端的所有列表,您不再需要担心错误

      【讨论】:

        【解决方案3】:
              List<String> items = ["Item1", "Item2", "Item3", "Item4"];
              String selectedItem = "";
              DropdownButton<String>(
              items: items.map(
              (txt) {
              return DropdownMenuItem<String>(
               child: Text(
               "$txt"
                   ),
                );
               }
               ).toList(),
               value: selectedItem==""null?"":selectedItem,
               )
        

        【讨论】:

          猜你喜欢
          • 2021-08-29
          • 2020-06-16
          • 2020-07-18
          • 1970-01-01
          • 2021-05-01
          • 1970-01-01
          • 2023-01-17
          • 2021-12-03
          • 2020-08-26
          相关资源
          最近更新 更多