Dart| Flutter How to calculate the collection numbers sum example
Functions in Dart return only a single value.
There are multiple ways to return multiple values wrapped with the below types
- Array or List
- Create an object of a Class
- Set
- Tuple class
How to return multiple values from a Function in Dart
Following are multiple ways to pass multiple data from a function
- create a class and pass the object with values from a function
In this example, the function wants to return multiples of different types, So Wrap those values in the object of a class and return from a function.
The function return type is Class and returns data, access data using properties of a class.
Here is an example code
class Employee {
final int id;
final String name;
Employee(this.id, this.name);
}
main() {
var employee = getData();
print(employee.id); // 1
print(employee.name); // john
}
Employee getData() {
return Employee(1, 'john');
}
- Wrap the multiple values in Array and List, return it from a function
In this example, the function return multiples of different types in a list or Array. So Wrap those values in square brackets and return them from a function.
The function return type is List and returns data, access data using list[index]
.
Here is an example code
main() {
var employee = getData();
print(employee[0]);
print(employee[1]);
}
List getData() {
return [1, 'john'];
}
- using tuple to combine multiple types
tuple🔗 is a new type from Google. It is used to combine multiple types into a single type. It provides a Tuple2
class.
Tuple2
object can be created with the below syntax
const t = Tuple2<int, String>(1, "string");
It contains two types int and string. Functions can return this object.
The values can be accessed with Tuple2.item1
and Tuple2.item2
properties.
Here is an example code
import 'package:tuple/tuple.dart';
Tuple2<int, String> getData() {
return new Tuple2(`42`, "john");
}
void main() {
final data = getData();
print(data.item1);
print(data.item2);
}
- use Set to return multiple type values in a function The function type is Set and returns multiple values.
The values from Set can be accessed using Set.first
and Set.last
properties.
Here is an example code
main() {
var employee = getData();
print(employee.first);
print(employee.last);
}
Set getData() {
return {1, 'john'};
}
Conclusion
To summarize, Dart or flutter functions return only a single type and values. However, We can do it using multiple ways - class objects, set, list, tuple, and Arrays