Records in Dart Language

Hi guys,

Today we will learn about Records in the Dart language and how we can use it.

What is Records?

Records are a kind of datatype that allows us to return multiple values at the same time.

Note

You are able to use Records in Dart 3.0 or higher version.

Let’s take an example, when we create a function for some processing after that function will return a single value. If we want more values to return, then we need to create a class for that add all the values to that class, and return that same class object.

But in Dart Records, we don’t need to create a class for that we can return multiple values at the same time with a comma separator, and enclosed in parentheses.

Records are anonymous we don’t need to give a name for the value.

Records are immutable once we set value to records that will not change.

Records values will be any datatype, Integer, String, boolean, Map, double, list, set, and so on. You can use records combination of any datatype.

Syntax

(value1, value2, ...so on)

How we can use it?

We can use this in multiple ways in our dart code.

First

void main() {
  var value = ('hello', 'world');
  print('${value.$1} ${value.$2}');
}

Output:-

In the above code (‘hello’, ‘world’) is Records, those values are assigned to value variable.

In the print function, I am using $1 and $2 those objects are automatically generated by the variable according to the values in the Records type. If we have 4 values in Records, then we have $1, $2, $3, and $4 objects.

Second

void main() {
  var value = (name: 'hello', age: 25);
  print('name:- ${value.name} -->  age: ${value.age}');
}

Output:-

In this, we give records value to some reference object, so that we can use it with their object name. In the above code “hello” is assigned to the name object and “25” is assigned to the age object. And we used those objects to show output in our code.

Third

void main() {
  final (int? a, int? b)  = swapValue(a: 10, b: 20);

  print('a: ${a} --> b: ${b}');
}

(int? a, int? b) swapValue({int? a, int? b}) {
  return (b, a);
}

Output:-

In the above code, I am directly taking Record type values from the function’s return. In swapValue Function I am returning 2 values, as same we can return multiple values from a function without creating a class.

Official Doc for Records:- Click Here

I hope this will help you to understand how we can use Records in Dart.

Thanks, Regards and

Namaste