So, shall we begin?
1. forEach()
Runs a function on each element in the list
var fruits = [‘banana’, ‘pineapple’, ‘watermelon’];
fruits.forEach((fruit) => print(fruit)); // => banana pineapple watermelon
2. map()
Produces a new list after transforming each element in a given list
var mappedFruits = fruits.map((fruit) => ‘I love $fruit’).toList();
print(mappedFruits); // => ['I love banana', ‘I love pineapple’, ‘I love watermelon’]
3. contains()
Checks to confirm that the given element is in the list
var numbers = [1, 3, 2, 5, 4];
print(numbers.contains(2)); // => true
4. sort()
Order the elements based on the provided ordering function
numbers.sort((num1, num2) => num1 - num2); // => [1, 2, 3, 4, 5]
5. reduce(), fold()
Compresses the elements to a single value, using the given function
var sum = numbers.reduce((curr, next) => curr + next);
print(sum); // => 15const initialValue = 10;
var sum2 = numbers.fold(initialValue, (curr, next) => curr + next);
print(sum2); // => 25
6. every()
Confirms that every element satisfies the test
List<Map<String, dynamic>> users = [
{ “name”: ‘John’, “age”: 18 },
{ “name”: ‘Jane’, “age”: 21 },
{ “name”: ‘Mary’, “age”: 23 },
];var is18AndOver = users.every((user) => user[“age”] >= 18);
print(is18AndOver); // => true
var hasNamesWithJ = users.every((user) => user[“name”].startsWith('J'));
print(hasNamesWithJ); // => false
7. where(), firstWhere(), singleWhere()
Returns a collection of elements that satisfy a test.
// See #6 for users list
var over21s = users.where((user) => user[“age”] > 21);
print(over21s.length); // => 1var nameJ = users.firstWhere((user) => user[“name”].startsWith(‘J’), orElse: () => null);
print(nameJ); // => {name: John, age: 18}var under18s = users.singleWhere((user) => user[“age”] < 18, orElse: () => null);
print(under18s); // => null
firstWhere()
returns the first match in the list, while singleWhere()
returns the first match provided there is exactly one match.
8. take(), skip()
Returns a collection while including or skipping elements
var fiboNumbers = [1, 2, 3, 5, 8, 13, 21];
print(fiboNumbers.take(3).toList()); // => [1, 2, 3]
print(fiboNumbers.skip(5).toList()); // => [13, 21]
print(fiboNumbers.take(3).skip(2).take(1).toList()); // => [3]
9. List.from()
Creates a new list from the given collection
var clonedFiboNumbers = List.from(fiboNumbers);
print(‘Cloned list: $clonedFiboNumbers’);
As of Dart 2.0, the new
keyword is optional when instantiating objects.
10. expand()
Expands each element into zero or more elements
var pairs = [[1, 2], [3, 4]];
var flattened = pairs.expand((pair) => pair).toList();
print(‘Flattened result: $flattened’); // => [1, 2, 3, 4]var input = [1, 2, 3];
var duplicated = input.expand((i) => [i, i]).toList();
print(duplicated); // => [1, 1, 2, 2, 3, 3]
Conclusion
I hope this has been insightful and if this is your first exposure to Dart, read my first steps tutorial to grasp the basics. The example snippets for this article are available on DartPad.
So why are particular letters used?
Simplest answer is convention. In fact you can use any letters you like, achieving the same effect. However the common ones carry semantic meaning:
T
is meant to be a TypeE
is meant to be an Element (List<E>
: a list of Elements)K
is Key (in aMap<K, V>
)V
is Value (as a return value or mapped value)
This code below will work even when I don’t use any of the placeholder letters above. For example, see this snippet below:
This works although the placeholder used is A
. By convention T
would be used:
Generics are powerful in that they allow us to reuse the same class with various types:
Conclusion
You can use these methods combined with inbuilt support for template literals, allowing effective manipulation of strings:
Let’s start with:
1. contains()
This allows you to check whether the specified string exists:
2. startsWith()
This allows you to check whether the string starts with the specified characters:
3. endsWith()
Checks whether the string ends with the specified characters:
4. toLowerCase(), toUpperCase()
Converts the string to lowercase and uppercase formats:
5. split()
Splits the string at the matching pattern, returning a list of substrings:
6. splitMapJoin()
Splits the string, converts each list item, and combines them into a new string:
7. indexOf(), lastIndexOf()
Returns the position of the first and last matches of the given pattern:
Both methods also take in an optional parameter specifying the index to begin the search from:
8. trim()
Removes leading and trailing whitespaces:
9. padLeft(), padRight()
Pads the string on the left and right with the given padding if the string is less that the specified length:
10. replaceAll()
Replaces all substrings that match the specified pattern with the replacement string:
Conclusion
Top 10 Map/Object methods you should know
n 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.
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
3. containsValue()
Checks whether the given value exists
4. forEach()
Runs the given function over each key/value pair
5. putIfAbsent()
Adds a key/value pair if non-existent. If key already exists, a value will be set if there isn’t one.
6. remove()
Removes the provided key and its associated value
This will return the value that was removed.
7. removeWhere()
Removes the key/value pair if the given condition is true
8. clear()
Removes every key/value pair in the map
9. update()
Updates the value for the given key
This also returns the new value. To prevent an error being thrown should the key not exist, there’s a third parameter:
In most cases you could update using array bracket notation:
10. Map.from()
This technically is a constructor, but still useful as a utility. It creates and returns a copy of the provided map:
Conclusion
Here’s a complete solution:
No comments:
Post a Comment