简体   繁体   中英

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

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.

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}");
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM