numen31337 / copy_with_extension

Provides Dart Build System builder for generating copyWith extensions for annotated classes.
https://pub.dev/packages/copy_with_extension_gen
MIT License
74 stars 30 forks source link

[Easy Fix] CopyWith Function parameter is not null safe #93

Open tolotrasamuel opened 3 months ago

tolotrasamuel commented 3 months ago

I like your package compared to Freezed. However, I found an issue. Consider the following code

void main(){
  final int? someApiResult = null;
  final a = Income.empty().copyWith(value: someApiResult); // not null safe here
  print(a.value);
}

For the class:

import 'package:app_core/model/app/base_model/updatable_entity.dart';
import 'package:app_core/model/app/custom/income.model.dart';
import 'package:app_core/repository_helper/json_map.dart';
import 'package:app_core/utils/annotations/annotations.dart';
import 'package:copy_with_extension/copy_with_extension.dart';

part 'income.g.dart';

enum IncomeType {
  adReward,
  couponCode,
  refill,
}

@myJsonSerializable
@CopyWith()
class Income {
  final int value;
  final IncomeType type;
  final String incomeSourceId;

  Income({
    required this.incomeSourceId,
    required this.type,
    required this.value,
  });

  factory Income.fromJson(JsonMap json) => _$IncomeFromJson(json);

  JsonMap toJson() => _$IncomeToJson(this);

  factory Income.empty() => Income(
        incomeSourceId: "someID"
        value: 0,
        type: IncomeType.adReward,
      );

}

void main(){
  final someApiResult = null;
  final a = Income.empty().copyWith(value: someApiResult); // not null safe here
  print(a.value);
}

Could you please fix this? The problem is copyWith function parameters is not null safe. The compiler does not report the bug illustrated above. Normally, the developer forgot to write step that handle an edge case when the apiResult is null.

This will leads to unwanted behaviour at runtime. I checked the code. This seems like an easy fix:

Instead of generating code:

 Income call({
    String? incomeSourceId,
    IncomeType? type,
    int? value,
  });

Can you generate:

 Income call({
    String incomeSourceId,
    IncomeType type,
    int value,
  });
tolotrasamuel commented 2 months ago

https://github.com/numen31337/copy_with_extension/blob/7b62b4a68b8e2db9fae3d830347b87e4df1e8f19/copy_with_extension_gen/lib/src/copy_with_generator.dart#L175C2-L178C40

This is a the link of code that causes the issue, shouldn't it just be final type = v.type