Data Structures

Dart Records

Using Records

Dart records provide immutable structured data with pattern matching.

Introduction to Dart Records

Dart Records is a powerful feature introduced in Dart to handle structured data immutably. They are designed to make data handling more efficient and less error-prone by providing immutable data structures that support pattern matching.

In this guide, we'll delve into the basics of Dart Records, explore their syntax, and see how they can be utilized in real-world applications.

What are Dart Records?

Dart Records are immutable data structures that group multiple values into a single entity. Unlike traditional classes, records offer a lightweight syntax for creating data containers without requiring the boilerplate code typically associated with classes.

With records, you can easily manage and manipulate structured data while ensuring immutability, which can help prevent unintended side-effects in your programs.

Creating a Record

Creating a record in Dart is straightforward. Records are defined using parentheses and can store multiple values separated by commas. Here is an example of creating a simple record:

In this example, point is a record containing two integer values. Records can also store more complex types, such as strings and objects.

Accessing Record Elements

You can access elements of a record using positional syntax. Here's how you can retrieve values from the record:

The dot notation followed by a positional index allows you to access each element in the record. Indexing starts from $1 for the first element, $2 for the second, and so on.

Pattern Matching with Records

One of the standout features of Dart Records is their ability to support pattern matching. This allows you to deconstruct a record and extract its elements efficiently. Here’s an example:

In this code, pattern matching is used in a switch statement to deconstruct the record into its components. This makes it easy to work with complex data structures and implement logic based on the values stored in records.

Benefits of Using Dart Records

  • Immutability: Ensures data consistency and prevents accidental changes.
  • Pattern Matching: Simplifies code for working with structured data.
  • Lightweight Syntax: Reduces boilerplate code, making your code cleaner and easier to maintain.

Data Structures

Previous
Sets