I would like to have a list of tuples in dart/flutter, loop over them and read the first and second variable. There is a pub.dev package that creates a tuple in flutter. Is there another way in dart? Do I need to use a class to create a tuple like the flutter package does?
I began to create an example in dart pad
void main() {
List testList = [("a",1),("b",2),("c",3),("d",4),("e",5)];
for (var i = 0; i < 5; i++) {
print('hello $i');
currentItem = testList[i];
}
}
Example of how you can iterate over your data pairs by using a Map
as data structure:
void main() {
final testMap = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5};
for (final mapEntry in testMap.entries) {
final key = mapEntry.key;
final value = mapEntry.value;
print('Key: $key, Value: $value');
// Key: a, Value: 1
// Key: b, Value: 2
// Key: c, Value: 3
// Key: d, Value: 4
// Key: e, Value: 5
}
}
You can also rather easy introduce your own Pair
class which allows you to bind two objects together:
class Pair<T1, T2> {
final T1 a;
final T2 b;
Pair(this.a, this.b);
}
void main() {
final testList = [
Pair("a", 1),
Pair("b", 2),
Pair("c", 3),
Pair("d", 4),
Pair("e", 5)
];
for (final pair in testList) {
print('${pair.a} -> ${pair.b}');
}
// a -> 1
// b -> 2
// c -> 3
// d -> 4
// e -> 5
}
In most cases I will recommend you to make a class
for you specific need since it makes it easier to make type safe code.
Dart 3 came out in May 2023, and includes a new feature called Records
.
In most languages, a tuple has usually only positional fields, and a record has named fields. Dart combines these two. A Record
in dart can have both positional and named fields.
When you create a Record
with only positional fields, it's just a tuple:
var tuple = ("first", 2, true);
You can use it as return type for example:
(int, String) foo() {
return (1, "string");
}
It can be deconstructed like this:
var (a, b) = foo();
So your example code in Dart 3 would look something like this:
List testList = [("a",1),("b",2),("c",3),("d",4),("e",5)];
for (int i = 0; i < 5; i++) {
var (stringVal, intVal) = testList[i];
print('hello ${stringVal} ${intVal}');
}
This is the specification:
https://github.com/dart-lang/language/blob/main/accepted/3.0/records/feature-specification.md
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With