Streamlining Flutter Code with Records and Control Flow

Streamlining Flutter Code with Records and Control Flow

In the last article, we had a basic introduction to a new built-in collection type coming out in the Dart 3.0 release i.e. Records. If you've not gone through that article, I'll recommend giving it a quick read to have a quick refresher.

In this article, we're going to look at one of the important applications of Records in the Flutter world which is Control Flow in Argument Lists.

Records in dart support both positional and named fields which makes it different from tuples in other programming languages that only support positional fields.

final record = (1, 2, x: 3, y: 4);

If you're not a Dart newbie, you must already be familiar that dart also supports positional as well as named parameters. Positional parameters are defined by their order in the constructor signature and are passed to the constructor in the same order as they appear in the signature.

Named parameters, on the other hand, are identified by a name and are passed to the constructor using a name-value syntax.

And if you're using Dart and Flutter for some time now, you might also be aware of the spread operator. It is basically used for unpacking a List object.

var list1 = [1, 2, 3];
var list2 = [4, 5, 6];
var combinedList = [...list1, ...list2];
print(combinedList); // [1, 2, 3, 4, 5, 6]

With Dart 3.0 we'll be able to eventually use it for unpacking a Record object also.

Since records also support both positional as well as named parameters we can make use of the spread operator to turn something like this:

  ListTile(
      leading: const Icon(Icons.alarm),
      title: const Text('Wake Up!'),
      enabled: isPastFiveAM,
      subtitle: isPastFiveAM ? const Text('Tap to dismiss the alarm')                             
                : null,
      onTap: isPastFiveAM ? dismissAlarm : null,
      trailing: isPastFiveAM ? Icon(Icons.sunny) : null,
    );

into:

ListTile(
      leading: const Icon(Icons.alarm),
      title: const Text('Wake Up!'),
      enabled: isPastFiveAM,
      if(isPastFiveAM)
      ...(
      subtitle: const Text('Tap to dismiss the alarm'),
      onTap: dismissAlarm,
      trailing: Icon(Icons.sunny),
      )
    );

Pretty neat, right?

So that's all for this article. In the next article in this series, we'll look into Pattern matching for JSON destructuring in Dart 3.0.