Top 10 Array utility methods you should know (Dart)

 So, shall we begin?


1. forEach()

Runs a function on each element in the list

2. map()

Produces a new list after transforming each element in a given list

3. contains()

Checks to confirm that the given element is in the list

4. sort()

Order the elements based on the provided ordering function

5. reduce(), fold()

Compresses the elements to a single value, using the given function

6. every()

Confirms that every element satisfies the test

7. where(), firstWhere(), singleWhere()

Returns a collection of elements that satisfy a test.

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

9. List.from()

Creates a new list from the given collection

As of Dart 2.0, the new keyword is optional when instantiating objects.

10. expand()

Expands each element into zero or more elements

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 Type
  • E is meant to be an Element (List<E>: a list of Elements)
  • K is Key (in a Map<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:

class CacheItem<A> { // Using the letter A
CacheItem(A this.itemToCache);
final itemToCache;
String get detail => '''
Cached item: $itemToCache
The item type is $A
''';
}
void main() {
var cached = CacheItem<int>(1);
print(cached.detail);
// Output:
// Cached item: 1
// The item's type is int
}

This works although the placeholder used is A. By convention T would be used:

class CacheItem<T> {
CacheItem(T this.itemToCache);
final itemToCache;
String get detail => '''
Cached item: $itemToCache
The item type is $T
''';
}

Generics are powerful in that they allow us to reuse the same class with various types:

CacheItem<String> cachedString = CacheItem<String>('Hello, World!');
print(cachedString.detail);
// Output:
// Cached item: Hello, World!
// The item's type is String
var cachedInt = CacheItem<int>(30);
print(cachedInt.detail);
// Output:
// Cached item: 30
// The item's type is int
var cachedBool = CacheItem<bool>(true);
print(cachedBool.detail);
// Output:
// Cached item: true
// The item's type is bool

Conclusion


You can use these methods combined with inbuilt support for template literals, allowing effective manipulation of strings:

var str1 = 'Lorem';
var str2 = '$str1 ipsum'; // String interpolation
var str3 = '''Multi
Line
$str1 $str2'''; // Multi-line strings

Let’s start with:

1. contains()

This allows you to check whether the specified string exists:

str1.contains('rem'); // true

2. startsWith()

This allows you to check whether the string starts with the specified characters:

str2.startsWith('Lorem'); // true
str3.startsWith('Noorem'); // false

3. endsWith()

Checks whether the string ends with the specified characters:

str3.endsWith('ipsum'); // true
str3.endsWith('oopsum'); // false

4. toLowerCase(), toUpperCase()

Converts the string to lowercase and uppercase formats:

str1.toLowerCase(); // lorem
str1.toUpperCase(); // LOREM

5. split()

Splits the string at the matching pattern, returning a list of substrings:

str3.split('\n'); // ['Multi', 'Line', 'Lorem Lorem ipsum'];

6. splitMapJoin()

Splits the string, converts each list item, and combines them into a new string:

str3.splitMapJoin(RegExp(r'^', multiLine: true), // Matches the beginning of each line
onMatch: (m) => '**${m.group(0)} ', // Adds asterisk to the line beginning
onNonMatch: (n) => n); // Leaves non matches as is
/*
Output:
** Multi
** Line
** Lorem Lorem ipsum
*/

7. indexOf(), lastIndexOf()

Returns the position of the first and last matches of the given pattern:

str3.indexOf('rem'); // 13
str3.lastIndexOf('rem'); // 19

Both methods also take in an optional parameter specifying the index to begin the search from:

str3.lastIndexOf('rem', 18); // 13

8. trim()

Removes leading and trailing whitespaces:

" $str2 ".trim(); // 'Lorem ipsum'

9. padLeft(), padRight()

Pads the string on the left and right with the given padding if the string is less that the specified length:

str1.padLeft(8, 'x'); // xxLorem
str1.padRight(8, 'x'); // Loremxx

10. replaceAll()

Replaces all substrings that match the specified pattern with the replacement string:

str2.replaceAll('e', 'é'); // Lorém

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.

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


Here’s a complete solution:

class Order {
// private properties
int _id;
String _reference;
DateTime _date;
// public properties
String code;
String from;
List<String> bookings;
Order(this._id, this._reference, this._date);
Order.withDiscount(this._id, this._reference, {this.code}) {
_date = new DateTime.now();
}
// Using doc strings to save the multiple linebreaks(\n)
String getInfo() => '''
Your order information:
-------------------------------
Id: $_id
Reference: $_reference
Date: $_date
-------------------------------
''';
void printInfo() => print(getInfo());
}
void main() {
Order order1 = new Order.withDiscount(1, 'ref1', code: 'SPECIALDISCOUNT')
..from = 'Jermaine Oppong'
..bookings = ['booking1', 'booking2', 'booking3']
..printInfo();
}

Conclusion




Comments

Popular posts from this blog

Easy Text-to-Speech with Python

Flutter for Single-Page Scrollable Websites with Navigator 2.0

Better File Storage in Oracle Cloud