Skip to content
Related Articles

Related Articles

Flutter – Using Tuples

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 08 Feb, 2022

A tuple is a collection of items that could be dissimilar. It is the list-like data type. Since it is not a built-in data type in Flutter we need a tuple package to include it in the project. Let’s discuss tuple in the Flutter in this article.

Add in the Dependency:

In Flutter, a tuple needs to be added as a dependency in pubspec.yaml. Then run pub get to install it.

Import in main.dart:

To add tuple functionality, add it in main.dart.

Dart




import 'package:tuple/tuple.dart';

Example 1:

The tuple can be created of different sizes up to length 7 in Flutter. Let us see an example where we create a tuple of size 2. The items in the tuple are dynamic, independent of data type. We declared a const variable t and initialized it as a tuple. Then we print the values stored in t by accessing them through item1, and item2. 

Dart




const t = Tuple2<String, int>('geeksforgeeks', 10);
print(t.item1);
print(t.item2);

Output: 

Example 2:

We created a tuple t2 of length 2 and accessed the item1 which is “geeksforgeeks”. Then, we replaced the value of the third item of the tuple using the withItem3() function. The third item value which is 10 will be replaced as 20. 

Dart




const t2 = Tuple3('geeksforgeeks', 'tutorial', 10);
print(t2.item1);
print(t2.withItem3(20));

Output:

Example 3:

Let’s declare a tuple of length 7 and then convert it into the list using the toList() method.

Dart




const t3 = Tuple7(1, 2, 3, 4, 5, 6, 7);
print(t3.toList());

Output: 

Example 4:

We can also create a tuple from a list. For example, declare a list of integers items and then use the tuple of size items length and use the fromList() method to convert that list into a Tuple.

Dart




List items = [1, 2, 3, 4, 5, 6];
var t4 = Tuple6.fromList(items);
print(t4);

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!