flutter - 是否可以在 Flutter/Dart 中创建不止一种类型的列表?

标签 flutter dart

假设有两个不相关的类(来自 Flutter 库等):

class A {
   String name;
}

class B {
   int age;
}

有可能有一个List<A/B>吗? ?我知道有可能 List<dynamic>但这也允许 Cs、Ds 和 Zs 被接受。

最佳答案

您可以为AB 创建一个父抽象类,并添加一个List,它只允许来自父类的子类。

abstract class Foo {

}


class A extends Foo {

}

class B extends Foo {

}

class C {

}

这是正确的:

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

这不是

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

并且您可以使用自己的变量或使用 runtimeType

来标识类型
  for(Foo item in items){
    print(item.runtimeType);
  }

另一种选择(长版)

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 {

}

用法

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

关于flutter - 是否可以在 Flutter/Dart 中创建不止一种类型的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56520273/

相关文章:

dart - 为什么现在可以使用可调用类呢?

flutter - 如何在命名构造函数中使用异步?

任务应用程序 :mergeDebugNativeLibs and app:mergeDebugJavaResource 的 Flutter 失败

即使我测试了数据是否正确,Flutter Provider 也没有更新我的 Widget?

firebase - Flutter/Dart/Firestore : How can I add a list of maps to firebase?

dart - double.infinity 和 MediaQuery 有什么区别?

android - Flutter,如何在同一设备上发布和调试应用程序?

Flutter淡入淡出动画总是显示黑屏

Flutter 将函数传递给 TextEditingController(text)

dart - flutter - 创建一个从 minHeight 开始,增长到 maxHeight 的盒子的正确方法