JsonSerializable 类 上的方法导致错误

Methods on JsonSerializable classes causing error

当我在下面添加 getter color 时,它不再创建 fromJson 方法。当我 运行 我的应用程序时出现此错误:

Error: Method not found: 'Alert.fromJson'.

怎么会?我以为 @JsonKey(ignore: true) 会忽略它?我不能把方法放在 JsonSerialzable 类 上吗?

import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:new_day_flutter/domain/entity/alert/alert_enum.dart';
import 'package:new_day_flutter/domain/entity/alert/alert_severity.dart';
import 'package:new_day_flutter/presentation/theme/palette.dart';

part 'alert.g.dart';

@JsonSerializable(constructor: '_', createFactory: true)
class Alert extends Equatable {
  final AlertEnum alert;
  final DateTime time;
  final AlertSeverityEnum severity;

  const Alert._(
      {required this.alert, required this.time, required this.severity});

  factory Alert.highAlarm({required DateTime time}) {
    return Alert._(
        alert: AlertEnum.highAlarm,
        time: time,
        severity: AlertSeverityEnum.medium);
  }

  factory Alert.lowAlarm({required DateTime time}) {
    return Alert._(
        alert: AlertEnum.lowAlarm,
        time: time,
        severity: AlertSeverityEnum.medium);
  }

  factory Alert.lockout({required DateTime time}) {
    return Alert._(
        alert: AlertEnum.lockout, time: time, severity: AlertSeverityEnum.high);
  }

  factory Alert.solutionLow({required DateTime time}) {
    return Alert._(
        alert: AlertEnum.solutionLow,
        time: time,
        severity: AlertSeverityEnum.low);
  }

  @JsonKey(ignore: true)
  Color get color {
    if (severity == AlertSeverityEnum.high) {
      return errorRed;
    }
    if (severity == AlertSeverityEnum.medium) {
      return warningOrange;
    }
    if (severity == AlertSeverityEnum.low) {
      return bluelabBlue;
    }

    return bluelabBlue;
  }

  @override
  List<Object> get props => [alert, time, severity];

  Map<String, dynamic> toJson() => _$AlertToJson(this);
}

json_serializable 将生成 fromJson 的实现,但它不能向您的 class 添加工厂或静态方法。您必须自己创建工厂(并让生成的实现完成所有实际工作):

  factory Alert.fromJson(Map<String, dynamic> json) => _$AlertFromJson(json);

您可能在添加 color getter 时不小心删除了该代码。