loading...
Cover image for Top 10 Map/Object utility methods you should know (Dart) 🎯

Top 10 Map/Object utility methods you should know (Dart) 🎯

graphicbeacon profile image Jermaine Oppong Updated on ・2 min read

In this article we will look at the top 10 utility methods you should know about the Map type in Dart. This is a sister article to the earlier "Top 10" I did on Array/List types, so let's jump right into it.


1. addAll()

This allows you to merge all key/value pairs of the provided map to the current one.

var user = {
  "firstName": "Tom",
  "age": 25,
};

user.addAll({
  "lastName": "Smith",
  "age": 26,
});

print(user); // => {"firstName": "Tom", "age": 26, "lastName": "Smith"}

If a key already exists, its value will be replaced. This works similarly to Object.assign in JavaScript.

2. containsKey()

Checks whether the given key exists

print(user.containsKey("age")); // => true
print(user.containsKey("accessToken")); // => false

3. containsValue()

Checks whether the given value exists

print(user.containsValue("Smith")); // => true
print(user.containsValue(40)); // => false

4. forEach()

Runs the given function over each key/value pair

user.forEach((key, value) => print('Key: $key, Value: $value')); // => "Key: firstName, Value: Tom" "Key: age, Value: 26" "Key: lastName, Value: Smith"

5. putIfAbsent()

Adds a key/value pair if non-existent. If key already exists, a value will be set if there isn't one.

user.putIfAbsent("accessToken", () => "abf329jklr90rnlk2..."); // => {"firstName": "Tom", "age": 26, "lastName": "Smith", "accessToken": "abf329jklr90rnlk2..."}

6. remove()

Removes the provided key and its associated value

user.remove("accessToken"); // => abf329jklr90rnlk2...

This will return the value that was removed.

7. removeWhere()

Removes the key/value pair if the given condition is true

user.removeWhere((key, value) => key == "lastName");

8. clear()

Removes every key/value pair in the map

user.clear();
print(user); // => {}

9. update()

Updates the value for the given key

user["age"] = 25;
user.update("age", (dynamic val) => ++val); // => 26

This also returns the new value. To prevent an error being thrown should the key not exist, there's a third parameter:

user.update("name", (dynamic val) => "Jim", ifAbsent: () => "Jane");
print(user); // => {"age": 26, "name": "Jane"};

In most cases you could update using array bracket notation:

user["name"] = "Mary";

10. Map.from()

This technically is a constructor, but still useful as a utility. It creates and returns a copy of the provided map:

var userCopy = Map.from(user);

Conclusion

I hope this was insightful and if this is your first exposure to Dart, read my first steps tutorial to grasp the basics. The code snippets for this article are available on DartPad.

Like and follow me 😍 for more articles on Dart. Thanks so much.

Quicklinks

  1. Map<K,V> class Documentation
  2. Free Dart screencasts on Egghead.io

Continue reading:


Posted on Jul 23 '18 by:

graphicbeacon profile

Jermaine Oppong

@graphicbeacon

Web Developer | Google Dart enthusiast | Egghead.io instructor | YouTuber πŸ“Ή | Read my blog ✍🏾 https://www.creativebracket.com

Discussion

markdown guide
 

This post actually wants me to get back to rewriting a personal project I have in Dart. I started to earlier this year to help me learn Dart. I think I should get back into it. Enjoyed the language in the short time I spent in it.

 

Please do, and share with us when finished. I'll still be here :)

 

I've enjoyed playing around with Dart lately. With Flutter it's finally getting its time in the sun.

 

Hey Ben, it's great to hear that you dived into Dart. It's reassuring that the response has mostly been positive. With Dart 2 Stable around the corner, I'm more confident in choosing Dart for future projects.

 

I learned Dart some years ago, just after v1 was released, and I really liked it, but never used it again.

With the new versions of JS and TypeScript, is there any particular use case where Dart would be recommended nowadays?

 

Hey Daniel,

Thanks for your question and sharing your Dart journey.

The strongest use case right now is mobile app development, thanks to the Flutter framework. Also Dart is said to be the language for building apps on Google Fuchsia OS at this present time.

Things have changed since v1, including the tools for clientside development.

It's especially useful when building large applications with a tooling ecosystem that allows for strong typing, debugging, IDE integration and so on. I found the experience productive when I built this game, since it came with all the tools needed.

 

Ok, reading about Flutter over and there for some while, currently installing while reading this article. Let's see what happens next:)

 

Can't wait to see what you do with this knowledge :)