Flutter Records : Just a taste

Miyuru Sanjana
2 min readAug 13, 2024

--

With Records coming to the Dart language, Flutter devs are in for a treat. The way we work with data structures and function results is now a little more elegant and simple thanks to this new feature. In this short article, we’ll look at the idea of Records and show how they can be used in real life with some sample code.

Made with Canva

What are Flutter Records?

According to the docs , Records are an anonymous, immutable, aggregate type. Like other collection types, they let you bundle multiple objects into a single object.

Not Clear enough! then understand record is like a simple box that holds a few related pieces of information together. For example, if you have a person’s name and age, you can store both in one record instead of making a new class. Records are fixed, so once you put something in, you can’t change it. They’re a quick way to group and use related data without extra complexity.

Syntax

Creating a Record is straightforward. Here’s the basic syntax,

(type1 fieldName1, type2 fieldName2, ...) recordName = (value1, value2, ...);

Practical Use Cases

1. Returning Multiple Values from Functions

(String name, int age) getUserDetails() {
return ('Alice', 30);
}

void main() {
var (name, age) = getUserDetails();
print('Name: $name, Age: $age');
}

I know what you thought when you saw this(Yeah Functional Programming/ eg:Dartz). I Will write an in-depth usage in upcoming articles.

2. Data Structures

(double latitude, double longitude) coordinates = (40.7128, 74.0060);

void main() {
print('Latitude: ${coordinates.latitude}, Longitude: ${coordinates.longitude}');
}

3. Pattern Matching (Simulating JSON)

var jsonResponse = (id: 101, name: 'Product A', price: 99.99);

void main() {
var (id, name, price) = jsonResponse;
print('ID: $id, Name: $name, Price: $price');
}

Although Dart have native pattern matching for JSON, Records can also be effectively mimic this behaviour. In this code, we treat a Record as if it were a JSON response and extract the values using de-structuring.

Don’t Forget Immutability (Once created, the values within a Record cannot be changed, ensuring data integrity)

Now that Records is fully built into Dart 3, Flutter developers have a powerful tool for handling data. Don’t be afraid to use the elegance and speed that Records bring to your apps as you work on them.

I know this is a short article and I only wrote this to give some taste about this new type(Of course more advanced practical use cases will come later/So don’t forget to follow to get updates 😉),Also Don’t forget to drop me a few claps 👏 👏 👏 … !

--

--

Miyuru Sanjana
Miyuru Sanjana

Written by Miyuru Sanjana

Im a Skilled full stack and mobile developer with over four years of experience in the tech industry.

Responses (1)