numen31337/copy_with_extension

Mismatch field type error in latest version `5.0.1`

zeshuaro opened this issue · 3 comments

Describe the issue

The following code used to work fine with 5.0.0:

import 'package:copy_with_extension/copy_with_extension.dart';
import 'package:flutter/material.dart';

part 'foo.g.dart';

@CopyWith()
class Foo {
  final ThemeData themeData;

  Foo({ThemeData? themeData}) : themeData = themeData ?? ThemeData();
}

But seems like something has changed in 5.0.1 and now the build runner fails with the error:

[SEVERE] copy_with_extension_gen on lib/foo.dart:

The nullability of the constructor parameter "themeData" does not match the nullability of the corresponding field in the object.
package:hello_world/foo.dart:7:7
  ╷
7 │ class Foo {
  │       ^^^
  ╵

I understand the error and I guess I can mark the field as nullable, but the field is not actually nullable as it does get initialised in the constructor.

So my question is, can copy_with_extension continue to support the above snippet? Or do I have to update my code?

Environment details

Paste the flutter environment detail.

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.7.0, on macOS 13.2.1 22D68 darwin-arm64, locale en-AU)
[✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.3)
[✓] VS Code (version 1.75.1)
[✓] Connected device (2 available)
[✓] HTTP Host Availability

• No issues found!

Paste the package version.

dependencies:
  flutter:
    sdk: flutter
  copy_with_extension: 5.0.1

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: ^2.1.7
  copy_with_extension_gen: 5.0.1

To Reproduce

Steps to reproduce the behaviour:

  1. Use the above snippet
  2. Install copy_with_extension: 5.0.1
  3. Run build runner
  4. Error will be outputted

Expected behaviour

Build runner building with copy_with_extension should work with the above snippet.

Additional context

N/A

Hi @zeshuaro, just to clarify, the latest release includes this specific behavior that was intended. This change was made because the library cannot predict or control any custom behavior in the constructor, and therefore cannot ensure that the "themeData" variable will have a non-null value.

I will take a closer look at this today. In fact, I had intended to throw an error in the opposite scenario - when the field is nullable, but the constructor parameter is non-nullable. Looks like an unintended side effect. 👍

Thanks for the quick fix!