Home > other >  add a map inside map and retrieve it from Firestore - Flutter
add a map inside map and retrieve it from Firestore - Flutter

Time:09-11

The scenario is, am trying to record a history of the challenges that user have participated in, the history only takes name, date, and isWin information from the challenge which will be showed later on "my Challenges" page for each user.

after a while thinking on how to solve this problem i came up with the logic of adding a map to the user model called challengesHistory, inside this map the information of each challenge that user participated in will be stored as another map inside the big map so it will become something like this:

Map challengeHistory = {
   "challenge-1": {"name": "", "date": "", "isWin": ""}
}

i have added the map to the user model correctly, now my problem is how to add new map each time user clicks on "participate" so it becomes:

Map challengeHistory = {
   "challenge-1": {"name": "", "date": "", "isWin": ""}
   "challenge-2": {"name": "", "date": "", "isWin": ""}
}

and each time user participate in a challenge it adds challenge-4 ,5 ,6 ... and so on

code of the button when user clicks on "participate":

FirebaseFirestore.instance.collection("Users").doc(user!.uid).update({
        'points': loggedInUser.points!   3,
        'challenges': loggedInUser.challenges!   1,
        'challengeMember': FieldValue.arrayUnion([widget._challengeName]),});

so using this code how can i add a new map inside "challengeHistory" map.

my second question is if i want to retrieve an information like the name of the fourth challenge how can i do that.

last thing how to iterate the whole "challengeHistory" map and print each challenge information.

i would be thankful for help.

CodePudding user response:

Try make challengeHistory a List<Map> so you can simply call challengeHistory.add() to add other challenges (Map).

Then you can also call challengeHistory[3]["name"] to get for example the name of the fourth challenge.

You can also loop through each challenge inside of the list:

for(var c in challengeHistory)
{
   print(c["name"]);
   print(c["date"]);
   print(c["isWin"]);
}
  • Related