Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

casting

dart

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>.

like image 328
dam034 Avatar asked Nov 27 '25 10:11

dam034


1 Answers

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();
like image 94
Christopher Moore Avatar answered Dec 01 '25 21:12

Christopher Moore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!