Viewed   4.4k times

I am trying to create a dropdown button in Flutter. I am getting a List from my database then I pass the list to my dropdownButton everything works the data is shown as intended but when I choose an element from it I get this error:

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

I tried setting DropdownButton value to null it works but then I can't see the chosen element.

Here is my code:

FutureBuilder<List<Tag>>(
    future: _tagDatabaseHelper.getTagList(),
    builder: (BuildContext context, AsyncSnapshot<List<Tag>> snapshot) {
      if (!snapshot.hasData) {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
      return ListView(
        children: <Widget>[
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.2,
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: MediaQuery.of(context).size.width * 0.07),
            child: Theme(
              data: ThemeData(canvasColor: Color(0xFF525A71)),
              child: DropdownButton<Tag>(
                value: _selectedTag,
                isExpanded: true,
                icon: Icon(
                  Icons.arrow_drop_down,
                  size: 24,
                ),
                hint: Text(
                  "Select tags",
                  style: TextStyle(color: Color(0xFF9F9F9F)),
                ),
                onChanged: (value) {
                  setState(() {
                    _selectedTag = value;
                  });
                },
                items: snapshot.data.map((Tag tag) {
                  return DropdownMenuItem<Tag>(
                    value: tag,
                    child: Text(
                      tag.tagTitle,
                      style: TextStyle(color: Colors.white),
                    ),
                  );
                }).toList(),
                value: _selectedTag,
              ),
            ),
          ),

I used futureBuilder to get my List from database.

 Answers

4

Well, since no problem has an exact same solution. I was facing the same issue with my code. Here is How I fixed this.

CODE of my DropdownButton:

DropdownButton(
   items: _salutations
         .map((String item) =>
             DropdownMenuItem<String>(child: Text(item), value: item))
         .toList(),
    onChanged: (String value) {
       setState(() {
         print("previous ${this._salutation}");
         print("selected $value");
         this._salutation = value;
            });
          },
     value: _salutation,
),

The Error

In the code snippet below, I am setting the state for a selection value, which is of type String. Now problem with my code was the default initialization of this selection value. Initially, I was initializing the variable _salutation as:

String _salutation = ""; //Notice the empty String.

This was a mistake!

Initial selection should not be null or empty as the error message correctly mentioned.

'items == null || items.isEmpty || value == null ||

And hence the crash:

Solution
Initialize the value object with some default value. Please note that the value should be the one of the values contained by your collection. If it is not, then expect a crash.

  String _salutation = "Mr."; //This is the selection value. It is also present in my array.
  final _salutations = ["Mr.", "Mrs.", "Master", "Mistress"];//This is the array for dropdown
Sunday, November 13, 2022
 
chamaz
 
5

Try this

new DropdownButton<String>(
  items: <String>['A', 'B', 'C', 'D'].map((String value) {
    return new DropdownMenuItem<String>(
      value: value,
      child: new Text(value),
    );
  }).toList(),
  onChanged: (_) {},
)
Saturday, November 5, 2022
 
2

I was doing something similar with tasks (reassigning them in a plugin). As a "Update" plugin it didn't have any problems, but as "Create" it would fail with the message "There should be only one owner party for an activity"

To fix this change the "Create" plugin to simply set the ownerid (instead of executing the AssignRequest).

targetEntity.Attributes["ownerid"] = new EntityReference(SystemUser.EntityLogicalName, assignTo.Id);

This code goes in the Pre-operation stage.

Saturday, October 29, 2022
 
4

I found a workarround on the issue.

It seems like instead of rebuilding the DropDownFormField, Flutter just considers it as completely ok to keep it. In this case it is also even pretty stubborn.

As i could not find a way to rebuild the Field, I created a pretty nasty but working. Also still requires some polish.

I basically let flutter believe I provide a different widget each time.

class InputRowTest extends StatefulWidget {
  @override
  _InputRowTestState createState() => _InputRowTestState();
}

class _InputRowTestState extends State<InputRowTest> {
  List<String> list1 = ['Apples', 'Bananas', 'Peaches'];

  List<String> list1_1 = ['GreenApples', 'RedApples', 'YellowApples'];

  List<String> list1_2 = [
    'YellowBananas',
    'BrownBananas',
    'GreenBananas',
    'GreenApples'
  ];

  List<String> list1_3 = [
    'RedPeaches',
    'YellowPeaches',
    'GreenPeaches',
    'GreenApples'
  ];

  List<String> _fromparent;
  int _fromparentint;
  Widget ddbff;
  var selected;
  bool chance;

  Widget ddff(List<String> list, bool chance) {
    return (chance)
        ? DropdownButtonFormField(
            value: list[0], //Seems this value wont change.
            items: list.map((category) {
              return DropdownMenuItem(
                value: category,
                child: Container(
                  child: Text(category),
                ),
              );
            }).toList(),
            onChanged: (val) {
              print(val);
            },
          )
        : Container(
            child: DropdownButtonFormField(
              value: list[0], //Seems this value wont change.
              items: list.map((category) {
                return DropdownMenuItem(
                  value: category,
                  child: Container(
                    child: Text(category),
                  ),
                );
              }).toList(),
              onChanged: (val) {
                print(val);
              },
            ),
          );
  }

  @override
  void initState() {
    _fromparent = list1_1;
    _fromparentint = 0;
    selected = list1_1[0];
    chance = true;
    ddbff = ddff(_fromparent, chance);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    List<List<String>> subLists = [list1_1, list1_2, list1_3];
    _fromparent = subLists[_fromparentint];

    chance = !chance;
    ddbff = ddff(_fromparent, chance);

    return Center(
      child: Container(
        child: Row(
          children: <Widget>[
            Expanded(
              child: DropdownButtonFormField(
                value: list1[0],
                items: list1.map((category) {
                  return DropdownMenuItem(
                    value: category,
                    child: Container(
                      child: Text(category),
                    ),
                  );
                }).toList(),
                onChanged: (val) {
                  setState(() {
                    _fromparentint = list1.indexOf(val);
                  });
                },
              ),
            ),
            Expanded(
              child: ddbff,
            ),
          ],
        ),
      ),
    );
  }
}

Monday, October 10, 2022
3

You can do it in simple way, just create a simple list of strings and pass that list to dropdown menu.

Here's how:

  1. Update your getCitiesList() function:

    Future<List<String>> getCitiesList() async {
      Database db = await instance.database;
    
      final citiesData = await db.query(tblCities);
    
      if (citiesData.length == 0) return null;
    
      return citiesData.map((Map<String, dynamic> row) {
        return row["name"] as String;
      }).toList();
    }
    
  2. Add this inside your form page:

    //initialize these at top
    List<String> _citiesList = <String>[];
    String _city;
    
    void _getCitiesList() async {
      final List<String> _list = await databaseHelper.getCitiesList();
      setState(() {
        _citiesList = _list;
      });
    }
    
  3. Call _getCitiesList(); inside initState().

  4. Add this inside your build method:

    DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          value: _city,
          items: _citiesList.map((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value),
            );
          }).toList(),
          onChanged: (String newValue) {
          setState(() {
              _city = newValue;
          });
          },
    )),
    
Wednesday, October 12, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share