Skip to content

copy_with_misses_field

Reports a copyWith that leaves out a constructor parameter that stores a field, so the copy resets it. Pass the field on.

Tier
advisory
Scope
Dart
Lowest preset
strict
Fix
none

The creation in a copyWith that leaves out an optional parameter of the constructor it calls, where that parameter stores a field. The copy gets the parameter’s default, not the value of the object it copies.

  • A copyWith is an instance method of that name, of a class or of an extension on a class, whose body creates exactly one object of that class.
  • A parameter stores a field when it is a field formal parameter, or a super parameter whose chain ends at one.

It does not report:

  • the key of a Flutter widget, or a deprecated parameter;
  • a parameter that copyWith does not take but passes on, id: id, which is left out of the change on purpose;
  • a copyWith that creates no object of its class, or several;
  • a generated copyWith, such as that of a freezed class: it lives in its generated part, which is not judged.

A field reset on purpose, such as a cache or a one-time correction, is reported. Suppress it with the reason.

The miss appears when a field is added to the constructor and copyWith is not updated: every copy then silently resets that field. In the Flutter framework’s source, the rule found a copyWith that takes exitDuration and never passes it on.

Violating
class Item {
const Item({required this.id, this.label, this.count = 0});
final int id;
final String? label;
final int count;
Item copyWith({String? label}) => Item(id: id, label: label ?? this.label);
}
Corrected
Item copyWith({String? label, int? count}) =>
Item(id: id, label: label ?? this.label, count: count ?? this.count);

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:

// A copy starts with an empty cache on purpose.
// ignore: assay/copy_with_misses_field

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