dart-lang / linter

Linter for Dart.
https://dart.dev/tools/linter-rules
BSD 3-Clause "New" or "Revised" License
634 stars 170 forks source link

`prefer_const_constructors` : False positive on factory constructor for generic type #3802

Open khoadng opened 2 years ago

khoadng commented 2 years ago

Describe the issue When initialize an object with default value using factory constructor, warning will be showed. However if I add the const keyword, the code will fail to compile. Remove the type will result in runtime error.

To Reproduce

class Foo<T> {
  const Foo({
    required this.list,
  });

  // prefer_const_constructors warning here 
  factory Foo.bar() => Foo(
        list: <T>[],
      );

  Foo<T> copyWith({
    List<T>? list,
  }) => Foo(list: list ?? this.list);

  final List<T> list;
}

Expected behavior No warning

Additional context If I left out the type and apply the suggestion, the warning will disappear but it will result in error in the below case

void main() {
  final foo = Foo<int>.bar();
  // Unhandled Exception: type 'List<int>' is not a subtype of type 'List<Never>?' of 'list'
  final _ = foo.copyWith(list: [1, 2, 3]);
}
khoadng commented 2 years ago

Another false positive in this case also.

srawlins commented 4 months ago

This is a duplicate (or near enough) of https://github.com/dart-lang/linter/issues/1629