繁体   English   中英

是否可以使用多种类型在Flutter / Dart中创建List?

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

假设两个不相关的类(来自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 dart 错误期望值<object> ' 但得到的类型之一是 'List<dynamic> '<div id="text_translate"><p> 我有一个像这样的C类:</p><pre> class C { int? first; int? second; C({ this.first, this.second, }); }</pre><p> 我有两个类,其中一个从另一个扩展:</p><pre> class A { int? id; List&lt;C&gt;? list; A({ this.id, this.list, }); } class B extends A{ String? title; B({ this.title, list, ):super( list: list, ); }</pre><p> 在我的手肘中,我创建了 B 类的实例,如下所示,但出现此错误:</p><pre> B b = B(title: '', list: []); expected value of Type List&lt;C&gt; but got one of type List&lt;dynamic&gt;</pre><p> 我的问题在哪里?</p></div></dynamic></object>

[英]FLutter dart error expected value of Type 'List<Object>' but got one of type 'List<dynamic>'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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