JsonSerializable and JsonKey issue after upgrade on Flutter Freezed model
Asked Answered
M

2

7

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?

Major answered 29/10, 2021 at 19:2 Comment(1)
Any updates here ? I still see in latest freezed documentation that the same approach is recommendedMadi
N
11

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.

Nial answered 4/11, 2021 at 16:51 Comment(0)
C
1

Add this to analysis_options.yaml

analyzer:
  exclude:
    - "**/*.g.dart"
    - "**/*.freezed.dart"
  errors:
    invalid_annotation_target: ignore
Cropeared answered 19/4 at 3:0 Comment(1)
This doesn't workScholar

© 2022 - 2024 — McMap. All rights reserved.