Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"There should be exactly one item with [DropdownButton]'s value: Item1" error when using dropdownbutton in flutter

Tags:

flutter

dart

I am trying to use the dropdown menu in my flutter app but getting an error.

Here is the code:

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

In some questions, I saw that we have to initially set a variable to the value present inside our list. I have exactly done that but still getting an error.

Error Message:

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'

What is the error here?

Kindly comment if more information is needed.

like image 261
Aditya Dixit Avatar asked Oct 15 '25 21:10

Aditya Dixit


2 Answers

Here an example, the explanation in the code:

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: (itemValue) {  // update the selectedItem value
                setState(() {
                  selectedItem = itemValue!;
                });
              },
              items: items
                  .map<DropdownMenuItem<String>>((String value) => DropdownMenuItem<String>(
                  value: value, // add this property an pass the value to it
                  child: Text(value,)
              )).toList(),
            ),
          ])

        ],
      ),

    );
  }
}
like image 179
Wilson Toribio Avatar answered Oct 18 '25 13:10

Wilson Toribio


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,
)
like image 24
muhsin Avatar answered Oct 18 '25 13:10

muhsin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!