Error: Either zero or 2 or more [DropdownMenuItem]s were detected with the same value I/flutter (18363): 'package:flutter/src/material/dropdown.dart':

后端 未结 10 1400
借酒劲吻你
借酒劲吻你 2021-01-17 13:07

Error code Hi I\'m new to flutter and have a question about dropdownbutton regarding using the same values for multiple dropdownbutton.

From my understanding from th

10条回答
  •  南笙
    南笙 (楼主)
    2021-01-17 13:46

    This exception you have because of mistakes:

    1. No _value1 and _value2 initialization.
    2. When you initialize them make sure that _value1 and _value2 right from nameList e.g.
    _value1 = nameList[0];
    _value2 = nameList[3];
    

    this is important step with complex data type, but in your case

    _value1 = "Name1";
    _value2 = "Name4";
    

    will be sufficient.

    Full example:

      String _value1;
      String _value2;
    
      final List nameList = [
        "Name1",
        "Name2",
        "Name3",
        "Name4",
        "Name5",
        "Name6",
        "Name7",
        "Name8"
      ];
    
      /// initialization is here:
      @override
     void initState() {
        super.initState();
        _value1 = nameList[0];
        _value2 = nameList[3];
      }
    
      @override
      Widget build(BuildContext context) {
        return ListView(
          children: [
            Row(
              children: [
                Text('Name: '),
                Center(
                  child: DropdownButton(
                    value: _value1,
                    onChanged: (value) {
                      setState(() {
                        _value1 = value;
                      });
                    },
                    items: nameList.map(
                      (item) {
                        return DropdownMenuItem(
                          value: item,
                          child: new Text(item),
                        );
                      },
                    ).toList(),
                  ),
                ),
              ],
            ),
            Row(
              children: [
                Text('Name: '),
                Center(
                  child: DropdownButton(
                    value: _value2,
                    onChanged: (value) {
                      setState(() {
                        _value2 = value;
                      });
                    },
                    items: nameList.map(
                      (item) {
                        return DropdownMenuItem(
                          value: item,
                          child: new Text(item),
                        );
                      },
                    ).toList(),
                  ),
                ),
              ],
            ),
          ],
        );
      }
    }
    

提交回复
热议问题