【问题标题】:JsonSerializable and JsonKey issue after upgrade on Flutter Freezed modelFlutter Freezed 模型升级后的 JsonSerializable 和 JsonKey 问题
【发布时间】:2021-12-14 19:28:35
【问题描述】:

我的应用程序运行正常,但是在 pub upgrade --major-versions 之后,我在所有模型上都遇到了问题。 示例模型:

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);
}

问题:

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

为了让它能在几周前的上一次升级中正常工作,我在 pubspec.yaml 中为 json_annotation: '4.0.1' 和 json_serializable: '4.1.4' 设置了一个固定版本,但不知道是否有是另一种毫无问题地更新这些软件包的方法。

我错过了什么,我怎样才能达到与使用冻结之前相同的效果?

【问题讨论】:

    标签: flutter freezed json-serializable json-annotation


    【解决方案1】:

    作者知道这个限制as indicated here。就我个人而言,我不同意“仅禁用警告”的解决方案,因为它会使合法警告静音,这几乎不是一个有效的工程解决方案。其中提出的替代方案表示在您确定警告没有问题的任何用法之上添加以下评论:

    // 忽略:invalid_annotation_target

    这对于大型代码库也不是很好,但它让您有责任决定忽略什么,同时还允许您在其他地方收到有效警告。

    【讨论】:

      猜你喜欢
      • 2019-12-24
      • 2021-06-11
      • 2021-06-25
      • 2020-04-17
      • 2020-03-26
      • 1970-01-01
      • 2021-01-18
      • 2020-11-04
      • 2020-09-02
      相关资源
      最近更新 更多