JsonSerializable and JsonKey issue after upgrade on Flutter Freezed model

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?

Upvotes: 9

Views: 11011

Answers (3)

Tosin Peter
Tosin Peter

Reputation: 26

Add this to analysis_options.yaml file it will work

analyzer:
  errors:
    constant_identifier_names: ignore
    invalid_annotation_target: ignore
include: package:flutter_lints/flutter.yaml

Upvotes: 0

Linh Kiubo
Linh Kiubo

Reputation: 39

Add this to analysis_options.yaml

analyzer:
  exclude:
    - "**/*.g.dart"
    - "**/*.freezed.dart"
  errors:
    invalid_annotation_target: ignore

Upvotes: 3

Danny Allen
Danny Allen

Reputation: 949

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.

Upvotes: 11

Related Questions