当我在下面添加gettercolor
时,它不再创建fromJson
方法。我在运行应用程序时遇到此错误:
错误:找不到方法:"Alert.fromJson".
为什么?我以为@JsonKey(ignore: true)
会忽略它?我可以不把方法放在JsonSerializable类上吗?
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的实现,但它不能向类中添加工厂或静态方法。您必须自己创建工厂(并让生成的实现完成所有实际工作(:
factory Alert.fromJson(Map<String, dynamic> json) => _$AlertFromJson(json);
在添加color
getter时,您可能意外地删除了该代码。