Welcome to the world of Records in Dart 3.0, a language construct that allows developers to bundle multiple objects into a single object. In this blog, we will focus on the use of Records and its relationship with another data structure, Tuple, within the Flutter framework known as the Dart Tuple.
A Record is an immutable aggregate type. Unlike collection types, which contain homogeneous groups of objects, a Record, on the other hand, is capable of holding fixed-sized, heterogeneous, and typed objects.
With this flexible record type, developers have the liberty to create records with different field types; a feature that most object-oriented languages don't easily offer.
In Dart, record expressions are simply comma-delimited lists of named or positional fields, enclosed in parentheses. An example of creating var record could look like:
Dart provides features to create record types that have both named and positional fields. Named fields, which are included inside curly braces in a record type appearance, are crucial for creating a Flutter record. For instance:
All record fields are accessible via built-in getters. As records are immutable, fields do not have setters. Named fields expose getters of the same name, while positional fields use the name $, eliminating any ambiguity.
Here's an example:
To further streamline record field access, one can apply various patterns provided by the language.
The field types of a record help define its shape. Field types can differ within the same record, with the type system acknowledging each field’s type when the record is accessed.
The record type system acknowledges and treats identical records created by two unrelated libraries as being of the same type.
Two records are considered equal if they possess the same shape and corresponding fields bear the same values. Here, the term 'shape' refers to the set of fields, the fields’ types, and their names of a record. An example demonstrating this can be as follows:
Records in Dart automatically define hashCode and == methods based on the structure of their fields, enhancing their usability and management.
One remarkable feature of records is their ability to return multiple values from a function. This resourceful feature leverages Dart Tuple to destructure the values into local variables using pattern matching.
Though you can return multiple values without records, it often lacks type safety and increases verbosity.
This blog provided a closer examination of Records in Dart 3.0 and their usage in bundling multiple objects into a single object. We've discovered how the Dart Tuple, a variant of Record, and positioning parameters offer a myriad of benefits in structuring our Flutter applications.
The features and utilities showcased offer app developers a lot more flexibility and control, helping them to build more robust and manageable Flutter apps while encapsulating the true power of Dart 3.0.