Skip to content

Redundant "!" operator for non-nullable fields in copyWIth #1270

Description

@ChaserVasya

Describe the bug

Freezed generates redundant force unwrap operator (!) for non-nullable fields in copyWith methods when the constructor parameter is nullable but the field itself is non-nullable.

To Reproduce

import 'package:freezed_annotation/freezed_annotation.dart';

part 'example.freezed.dart';

@freezed
class ExampleState with _$ExampleState {
  ExampleState({
    String? value,
  }) : value = value ?? 'default';

  @override
  final String value; // non-nullable field
}

After running dart run build_runner build, the generated copyWith method contains:

ExampleState call({
  Object? value = freezed,
}) {
  return _then(
    ExampleState(
      value: freezed == value
          ? _self.value! // ← Redundant force unwrap here
          : value as String?,
    ),
  );
}

Expected behavior

Since _self.value is already non-nullable (type String), the force unwrap operator (!) should not be generated:

ExampleState call({
  Object? value = freezed,
}) {
  return _then(
    ExampleState(
      value: freezed == value
          ? _self.value // ← No force unwrap needed
          : value as String?,
    ),
  );
}

Environment:

  • freezed: ^3.0.6
  • freezed_annotation: ^3.0.0
  • Flutter 3.32.5 • channel stable • https://github.com/flutter/flutter.git
    Framework • revision fcf2c11572 (7 days ago) • 2025-06-24 11:44:07 -0700
    Engine • revision dd93de6fb1 (7 days ago) • 2025-06-24 07:39:37 -0700
    Tools • Dart 3.8.1 • DevTools 2.45.1

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions