Home > OS >  Create a list of DropDownMenuItem from a Map
Create a list of DropDownMenuItem from a Map

Time:10-30

I have a map of this type:

final Map<String,String> drinkNameToImage = {'Bloody Mary':'assets/drinks/bloody_mary.png',
  'Cuba Libre': 'assets/drinks/cuba_libre.png','Gin Tonic': 'assets/drinks/gin_tonic.png',
  'Margarita': 'assets/drinks/margarita.png', 'Martini': 'assets/drinks/martini.png',
  'Mojito' : 'assets/drinks/mojito.png', 'Pina Colada':'assets/drinks/pina_colada.png'};

And I want to create a DropDownButton with a list where every item contains the name of the cocktail and the image related to it.

I wrote this piece of code:

Widget build(BuildContext context) {
return DropdownButton(
    items: List.generate(drinkNameToImage.length, (int index) {
      return DropdownMenuItem(
          child: Container(
        padding: const EdgeInsets.only(bottom: 5.0),
        height: 100.0,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Image(image: AssetImage(drinkNameToImage.values.elementAt(index))),
            Text(drinkNameToImage.keys.elementAt(index))],
        ),
      ));
    }),
    onChanged: null);

}

but running it throws some errors

Failed assertion: line 1303 pos 12: 'widget.items!.where((DropdownMenuItem item) => item.value == widget.value).length == 1': is not true.

How can I solve?

CodePudding user response:

The DropdownMenuItem and DropdownButton are missing value property.

 DropdownButton<String?>(
        value: drinkNameToImage.keys.elementAt(0),
        items: List.generate(
          drinkNameToImage.length,
          (int index) {
            return DropdownMenuItem<String>(
              value: drinkNameToImage.keys.elementAt(index),
              child: Container(
                padding: const EdgeInsets.only(bottom: 5.0),
                height: 100.0,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                     Image(
                      image: AssetImage(
                        drinkNameToImage.values.elementAt(index),
                      ),
                    ),
                    Text(
                      drinkNameToImage.keys.elementAt(index),
                    )
                  ],
                ),
              ),
            );
          },
        ),
        onChanged: (v) {},
      ),

Make sure to provide unique value for each DropdownMenuItem.

  • Related