Search code examples
firebaseflutterdartflutter-dependenciesflutter-test

How to add dynamic List to flutter nested map


Need a help!

This is my data from firebase

{
  "Engineering" : ["EEE", "CSE", "EE"],
  "Marketing" : [ "SEO", "Online Marketing", "Digital Marketing"],
}

I am using a nested dropdown to show these data to users, receiving data is something like this

Map<String, List<String>> 

after selecting the dropdown, individual selection is something like this-

String _selectedCategory = "Engineering" ;
String _selectedSkill = "EEE" ;

at a time a user can select a category with a skill,

I want to create a dynamic map like this

{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "Selected Category 2" : [ "Selected Skill 1 from Category 2", "Selected Skill 2 from Category 2", "Selected Skill 3 from Category 2"],
}

I tried to achieve this-

  List<String> addedSkills = [];
  Map<String, List<String>> addedData = {};

inside dropdown

setState((){
   addedSkills.add(_selectedSkill);
   addedData.addAll({_selectedCategory: _addedSkills})
});

data is showing like this

{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from 
   Category 2", "Selected Skill 3 from Category 2"],

}

but I want data something like this

{
  "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
  "Selected Category 2" : [ "Selected Skill 1 from Category 2", "Selected Skill 2 from Category 2", "Selected Skill 3 from Category 2"],
}

Solution

  • Your output indicates that your _selectedCategory variable is not being upated before this line runs

    addedData.addAll({_selectedCategory: _addedSkills})
    

    addAll on a map will add any new key/value pairs and overwrite the value of any existing key. In your case, the value stored under the _selectedCategory key is being overwritten.

    You could test this by hard coding a new key

    addedData.addAll({'test_category': _addedSkills})
    

    Assuming your addedData map already has at least one key value pair your data will look something like this

    {
      "Selected Category 1" : ["Selected Skill 1 from Category 1", "Selected Skill 2 from Category 1", "Selected Skill 3 from Category 1"],
      "test_category" : ['selected skill'],
    }
    

    So your issue probably lies in the logic of updating the value of _selectedCategory from what is selected in the dropdown menu. If you need help with that then I suggest sharing that code.