Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

flutter - How to add a new pair to Map in Dart?

I caught the following errors when adding a new pair to a Map.

  • Variables must be declared using the keywords const, final, var, or a type name
  • Expected to find;
  • the name someMap is already defined

I executed the following code.

Map<String, int> someMap = {
  "a": 1,
  "b": 2,
};

someMap["c"] = 3;

How should I add a new pair to the Map?

I'd also like to know how to use Map.update.

question from:https://stackoverflow.com/questions/53908405/how-to-add-a-new-pair-to-map-in-dart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To declare your map in Flutter you probably want final:

final Map<String, int> someMap = {
  "a": 1,
  "b": 2,
};

Then, your update should work:

someMap["c"] = 3;

Finally, the update function has two parameters you need to pass, the first is the key, and the second is a function that itself is given one parameter (the existing value). Example:

someMap.update("a", (value) => value + 100);

If you print the map after all of this you would get:

{a: 101, b: 2, c: 3}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...