Type error when adding two derivatives of same base class in a List

放肆的年华 提交于 2020-12-26 07:44:53

问题


I have this code:

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

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'));

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

I want _elementsHere as List<Widget> instead of List<ShowingLocation>.


回答1:


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();



回答2:


Another option is as keyword.

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


来源:https://stackoverflow.com/questions/63193939/type-error-when-adding-two-derivatives-of-same-base-class-in-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!