Skip to content

typed_source_copied_with_from

Reports a collection copied with from out of elements that already have its type, as in List<int>.from(ints). Use of instead.

Tier
advisory
Scope
Dart
Lowest preset
recommended
Fix
writes of in place of from

A collection of the Dart libraries made with its from constructor out of elements that already have the type it holds: List<int>.from(ints), Set<num>.from(ints), Map<String, int>.from(prices), LinkedHashSet<int>.from(ids). The violation covers the constructor name.

It reports only where of gives a collection of the same type:

  • the type arguments are written, and the source’s element type is a subtype of them; or
  • they are inferred, and are exactly the source’s element type.

It does not report:

  • a dynamic source, or one with dynamic elements: List<String>.from(json['tags']);
  • elements of a wider type, which from casts at run time;
  • a collection whose inferred type arguments differ from the elements’: final copy = List.from(ints) is a List<dynamic>, while List.of(ints) would be a List<int>;
  • a class whose from and of do not take the same arguments after the first.

from takes elements of any type and casts each as it copies, so a wrong element type shows only at run time. of takes elements of the collection’s type, which the compiler checks, and copies them without a cast. Where the elements have that type already, of says the same and checks more.

Violating
List<int> copy(List<int> sizes) => List<int>.from(sizes);
Corrected
List<int> copy(List<int> sizes) => List<int>.of(sizes);

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression:

// Why it stays as written here.
// ignore: assay/typed_source_copied_with_from

// ignore_for_file: assay/typed_source_copied_with_from silences it in a whole file, and // ignore: typed_source_copied_with_from without the prefix works too. See Suppressions.