Dart 在列表中添加相同基类的两个派生时出现类型错误

Dart 在列表中添加相同基类的两个派生时出现类型错误,dart,casting,Dart,Casting,我有以下代码: List<Widget> _elementsHere = _locationsRegister .map((e) => ShowingLocation( num: e.num, name: e.name, icon: e.icon, )) .toList(); _elementsHere.insert(0, Text('h

我有以下代码:

List<Widget> _elementsHere = _locationsRegister
        .map((e) => ShowingLocation(
              num: e.num,
              name: e.name,
              icon: e.icon,
            ))
        .toList();
_elementsHere.insert(0, Text('hello'));
我收到一个错误,
Text
不是
ShowingLocation
的子类型,尽管它是一个小部件


我想要
\u element shere
作为
列表
而不是
列表
这可以通过在
映射
函数的泛型字段中指定对象类型来解决。由于您没有指定类型,因此假定它是ShowingLocation的一个iterable

改为这样做:

List\u elementsHere=\u locationsRegister
.地图((e)=>显示位置(
num:e.num,
姓名:e.name,
icon:e.icon,
))
.toList();

这可以通过在
map
函数的泛型字段中指定对象类型来解决。由于您没有指定类型,因此假定它是ShowingLocation的一个iterable

改为这样做:

List\u elementsHere=\u locationsRegister
.地图((e)=>显示位置(
num:e.num,
姓名:e.name,
icon:e.icon,
))
.toList();
另一个选项是关键字

List\u elementsHere=\u locationsRegister
.地图((e)=>(显示位置(
num:e.num,
姓名:e.name,
icon:e.icon,
)作为小部件)
.toList();
另一个选项是关键字

List\u elementsHere=\u locationsRegister
.地图((e)=>(显示位置(
num:e.num,
姓名:e.name,
icon:e.icon,
)作为小部件)
.toList();
List<Widget> _elementsHere = _locationsRegister
    .map((e) => (ShowingLocation(
          num: e.num,
          name: e.name,
          icon: e.icon,
        ) as Widget))
    .toList();