Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a List in Flutter/Dart with more than one type?

Tags:

flutter

dart

Assume two unrelated classes (from Flutter libraries, etc):

class A {
   String name;
}

class B {
   int age;
}

Is it possible to have a List<A/B>? I know it's possible to have List<dynamic> but that would allow for Cs, Ds and Zs to be accepted as well.

like image 739
StackOverflowed Avatar asked Dec 31 '25 03:12

StackOverflowed


1 Answers

You can create a parent abstract class for A and B and add a List which only allows children from the parent class.

abstract class Foo {

}


class A extends Foo {

}

class B extends Foo {

}

class C {

}

This is correct:

  List<Foo> items = [A(), B()];

This isn't

  List<Foo> items = [A(), B(),C()];

And you can identify the type with your own variable or using the runtimeType

  for(Foo item in items){
    print(item.runtimeType);
  }

Another option (long version)

class Bar {
  final A a;
  final B b;
  Bar({this.a, this.b}) {
    if (a == null && b == null || a != null && b != null) throw ArgumentError("only one object is allowed");
  }
}


class A  {

}

class B  {

}

class C {

}

Usage

  List<Bar> items = [Bar(a: A()), Bar(b: B())];

  for(Bar item in items){
    if (item.a != null) print("Item : ${item.a}");
    if (item.b != null) print("Item : ${item.b}");
  }
like image 80
diegoveloper Avatar answered Jan 06 '26 06:01

diegoveloper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!