David
David

Reputation: 528

How to add values of specific variables in a map

I am building a flutter application that takes some values from a user and stores them in a map. I use a pageviewbuilder to present the Items the user should enter like so:

                    RadioListTile(
                      title: Text('${outcomeScore[index].sectionOne}'),
                      value: 1, 
                      groupValue: selectedScore, 
                      activeColor: Colors.blue,
                      onChanged: (val){
                        setSelectedScore(val);
                        setState(() {
                          scoreText = outcomeScore[index].sectionOne;
                        });
                        print(val);
                        print(scoreText);
                      },
                      secondary:  Text("One"),
                    ),

                    RadioListTile(
                      title: Text('${outcomeScore[index].sectionTwo}'),
                      value: 2, 
                      groupValue: selectedScore, 
                      activeColor: Colors.blue,
                      onChanged: (val){
                        setSelectedScore(val);
                        setState(() {
                          scoreText = outcomeScore[index].sectionTwo;
                        });
                        print(val);
                        print(scoreText);
                      },
                      secondary:  Text("One"),
                    )

On the PageView, I use a next button to move to the next page. the next button adds the selected value to the map like so:

  Map<String, String> myMap= {
    'createdOn' : '$currentTime',
  };

myMap[outcomeScore[index].itemTitle] = scoreText;
myMap[outcomeScore[index].itemTitle + " Score"] = selectedScore.toString();

When all of this is done, I end up with a map that has values like:

createdOn: 2020-08-17 10:55:22.983934, TestOne: VFR, TestOne Score: 3, TestTwo: TSA, TestTwo Score: 4, TestThree: RTA, TestThree Score: 3,

This is what the map would look like on Json

{

"TestOne" : "VFR",
"TestOne Score" : "3",
"TestTwo" : "TSA",
"TestTwo Score" : "4",
"TestThree" : "RTA",
"TestThree Score" "3"

}

on the last pageview, I have a submit button instead of the next and on this, I would like to sum up all the values of the variables with "Score" at the end of it. Any ideas on how to do this? I will really appreciate the help.

Thanks.

Upvotes: 0

Views: 56

Answers (1)

Yadu
Yadu

Reputation: 3305

use foreach loop to traverse through the map

var sum = 0;
map.forEach((key, value) { 
    if(key.contains('Score')){
      //caution, throws if fails to parse
      sum += int.parse(value);
    }
  });

Upvotes: 1

Related Questions