Search code examples
flutterdartdart-pattern-matching

Destructure a record inside a MapEntry in Dart Flutter


I have the following code:

  const mapEntry = MapEntry(('John', 'Doe'), 24);
  final MapEntry(key: name, value: age) = mapEntry;
  final (firstName, lastName) = name;
  print('first name: $firstName');
  print('last name: $lastName');
  print('age: $age');

The output is:

first name: John
last name: Doe
age: 24

Is it possible to destructure the ('John', 'Doe') record to firstName and lastName at the same line of destructuring the mapEntry?


Solution

  • Yep, it's as simple as

      final MapEntry(key: (firstName, lastName), value: age) = mapEntry;