Records in Dart 3

Ranjan Bhagat
Triveous
Published in
2 min readJun 22, 2023

Dart 3 🎯 Allows you to make and use records. Records are collections of values that don’t change. Records are like tuples in other languages, but they have some cool features, like giving names to the values, comparing them easily, and returning more than one value from a function. In this blog post, I will tell you what records are, how to use them, and how they can make your code better and easier to read. 🚀

The world before records 😭 :

void main() {

final name = Name(first: "Ranjan", last: "Bhagat");

print(name);

}

class Name {

String first;
String last;

Name({required this.first, required this.last});

@override
String toString() => "$first $last";


}

Output:

Ranjan Bhagat

The world after records 😀 :

void main() {

final name = ("Ranjan", "Bhagat");

print(name);

}

Output:

(Ranjan, Bhagat)

I know what you think how will you use these values stored inside records? 🤔

We can destructure the records and store them into separate variables.

void main() {

final (first, last) = ("Ranjan", "Bhagat");

print("$first $last");

}

Output:

Ranjan Bhagat

As you can see with records you can simplify your code but this is not it, records also support name values.

void main() {

final (first: fName, last: lName) = getName(); //(first : "Ranjan", last: "Bhagat")

print("$fName $lName");

}

({String first, String last}) getName() =>
(first : "Ranjan", last: "Bhagat");

We can further simplify the above code by storing the values in a single variable and accessing it using dot(.).

void main() {
final name = getName(); //(first : "Ranjan", last: "Bhagat")

print("${name.first} ${name.last}");
}

({String first, String last}) getName() =>
(first : "Ranjan", last: "Bhagat");

As you can see records make life easy by simplifying the code. You can compare it with the code that we need to write before records and after it.

I hope you like👍 this blog.

Visit us:

https://triveous.com/

--

--