在列表中添加相同基类的两个派生类时发生类型错误 [英] Type error when adding two derivatives of same base class in a List

查看:48
本文介绍了在列表中添加相同基类的两个派生类时发生类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

List<Widget> _elementsHere = _locationsRegister
        .map((e) => ShowingLocation(
              num: e.num,
              name: e.name,
              icon: e.icon,
            ))
        .toList();

我已指定 List< Widget> ,但是如果我在控制台中打印 _elementsHere.runtimeType.toString(),则可以看到 List< ShowingLocation> .实际上,如果我添加以下代码:

I have specified List<Widget>, but if I print _elementsHere.runtimeType.toString() in console, I can see List<ShowingLocation>. In fact if I add this code:

_elementsHere.insert(0, Text('hello'));

我收到错误消息,尽管它是一个小部件,但 Text 不是 ShowingLocation 的子类型.

I receive error that Text isn't a subtype of ShowingLocation, despite it's a Widget.

我希望 _elementsHere 作为 List< Widget> ,而不是 List< ShowingLocation> .

推荐答案

这可以通过在 map 函数的generics字段中指定对象类型来解决.由于未指定类型,因此假定它是 ShowingLocation 的可迭代对象.

This can be solved by specifying the object type in the generics field of the map function. Since you're not specifying the type, it's being assumed to be an iterable of ShowingLocation.

相反,请执行以下操作:

Do this instead:

List<Widget> _elementsHere = _locationsRegister
        .map<Widget>((e) => ShowingLocation(
              num: e.num,
              name: e.name,
              icon: e.icon,
            ))
        .toList();

这篇关于在列表中添加相同基类的两个派生类时发生类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆