问题
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