JsonSerializable and JsonKey issue after upgrade on Flutter Freezed model

1,209

The author is aware of this limitation as indicated here. Personally I disagree with the solution of "just disable the warning" as it silences legitimate warnings, and this is almost never a valid engineering solution. An alternative proposed therein indicates adding the following comment above any usage where you are certain that the warning is not problematic:

// ignore: invalid_annotation_target

This isn't great either for large codebases, but it places the responsibility on you to decide what to ignore while also allowing you to receive valid warnings elsewhere.

Share:
1,209
Osmany Becerra Gonzalez
Author by

Osmany Becerra Gonzalez

Updated on December 01, 2022

Comments

  • Osmany Becerra Gonzalez
    Osmany Becerra Gonzalez over 1 year

    My app was running ok but after pub upgrade --major-versions I am getting problems on all models. Example model:

    import 'package:app_220/models/Leads/LeadFieldModel.dart';
    import 'package:flutter/foundation.dart';
    import 'package:freezed_annotation/freezed_annotation.dart';
    import 'package:intl/intl.dart';
    
    part 'LeadModel.freezed.dart';
    part 'LeadModel.g.dart';
    
    @freezed
    abstract class LeadModel with _$LeadModel {
      const LeadModel._();
    
      @JsonSerializable(fieldRename: FieldRename.snake)
      const factory LeadModel({
        required int id,
        int? formId,
        @JsonKey(name: 'contact__first_name', defaultValue: '')
        @Default('')
            String contactFirstName,
        @JsonKey(name: 'contact__last_name', defaultValue: '')
        @Default('')
            String contactLastName,
        @JsonKey(name: 'contact__email', defaultValue: '')
        @Default('')
            String contactEmail,
        @JsonKey(name: 'contact__phone', defaultValue: '')
        @Default('')
            String contactPhone,
        int? staffId,
        @Default('') String staffLastName,
        DateTime? creationTime,
        @Default('') String sourceUrl,
        @Default('') String sourceIp,
        @Default(0) int viewed,
        List<LeadFieldModel>? leadData,
      }) = _LeadModel;
    
      factory LeadModel.fromJson(Map<String, dynamic> json) =>
          _$LeadModelFromJson(json);
    }
    

    Problems:

    The annotation 'JsonSerializable' can only be used on classes
    The annotation 'JsonKey' can only be used on fields or getters
    ...
    

    In order to make it work on the previous upgrade a few weeks ago, I set a fixed version for json_annotation: '4.0.1' and json_serializable: '4.1.4' in the pubspec.yaml, but I wonder if there is another way to update those packages without any issue.

    What am I missing, how can I achieve the same effect as before using freezed?