Skip to content

List.toList() Type problem #55321

Closed
Closed
@feduke-nukem

Description

@feduke-nukem

This tracker is for issues related to:

  • Dart core libraries (dart:async, dart:io, etc.)

Some other pieces of the Dart ecosystem are maintained elsewhere.
Please file issues in their repository:

Let's assume I have such code:

void main() {
  final holder = Holder<B>(contents: [Content(data: B())]);

  test(holder);
}

sealed class A {}

class B extends A {}

class C extends A {}

class Content<S extends A> {
  final S data;

  Content({required this.data});
}

class Holder<S extends A> {
  final List<Content<S>> contents;

  Holder({required this.contents});
}

So if I use toList() I will get TypeError:

void test(Holder holder) {
  final contents = holder.contents.toList();

  contents.add(Content(data: B())); // TypeError
}

But List.of() doesn't produce that error:

void test(Holder holder) {
  final contents = List.of(holder.contents);

  contents.add(Content(data: B())); // Okay
}

I wonder why? toList() under the hood uses List.of() but the result is different. List.from and [...contents] cause no problem, only toList() does.

Also that will work:

void test(Holder holder) {
  final contents = holder.contents.map((e) => e)).toList();

  contents.add(Content(data: B())); // Okay
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    closed-as-intendedClosed as the reported issue is expected behaviortype-questionA question about expected behavior or functionality

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions