DEV Community

Sudhanshu Kumar Yadav
Sudhanshu Kumar Yadav

Posted on

Do you know the patterns?

Hello fellow Dartisans! I hope you're ready for an exciting journey into the heart of Dart 3.0. Released on 10th May 2023, this version introduced a flock of major language features: Patterns, Records, and Class Modifiers​​. So buckle up, because we're about to dive in and explore these features with some fun examples.

Patterns

Patterns, in Dart, serve as a new category of grammar. They allow you to match and destructure values, enabling the extraction of parts of an object's data in an easy and intuitive way. Let's see some of the examples I have been trying out since my B'day.

  • Extracting Information from a List
var numList = [1, 2, 3];
var [a, b, c] = numList;
print(a + b + c); // Prints 6
Enter fullscreen mode Exit fullscreen mode

Here we're using a list pattern to destructure the three elements from numList and assign them to new variables a, b, and c.

  • Swapping Variables
var (a, b) = ('left', 'right');
(b, a) = (a, b); // Swap.
print('$a $b'); // Prints "right left"
Enter fullscreen mode Exit fullscreen mode

In this case, a pattern is used to swap the values of two variables without declaring a third temporary one.

  • Destructuring Map Entries
Map<String, int> hist = {
  'a': 23,
  'b': 100,
};

for (var MapEntry(:key, value: count) in hist.entries) {
  print('$key occurred $count times');
}
Enter fullscreen mode Exit fullscreen mode

Here, an object pattern is used in a for-in loop to destructure the MapEntry objects that a <Map>.entries call returns, effectively iterating over the entries of a map.

  • Validating and Extracting JSON Data
var json = {
  'user': ['Lily', 13]
};
if (json case {'user': [String name, int age]}) {
  print('User $name is $age years old');
}
Enter fullscreen mode Exit fullscreen mode

In this example, a case pattern is used to validate and destructure a JSON object. If the object has the expected structure, the pattern destructures it into local variables, providing a declarative and less verbose way of handling JSON data.

Top comments (0)