Skip to content

Unexpected error when down-casting a List #2087

Closed
@esDotDev

Description

@esDotDev

This code will throw the error:
Uncaught Error: TypeError: Instance of 'Bar': type 'Bar' is not a subtype of type 'Foo'

void main() {
  List<Foo> fl= [Foo()];
  List<Mixin> l = fl.cast<Mixin>();
  l.add(Bar()); // this is the line that throws
}

class Foo with Mixin {}

class Bar with Mixin {}

mixin Mixin {}

If you rewrite it as this, it works as expected:

  List<Mixin> l = [Foo()];
  ...

If you replace the cast (or toList()) with a map().toList(), it will also work as expected:

List<Foo> fl= [Foo()];
List<Mixin> l = fl.toList(); // causes runtime error when bar is added later
List<Mixin> l = fl.map((i) => i as Mixin).toList() // works as expected
l.add(Bar());

This is not specific to mixins, class + extends has identical behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions