Reputation: 12433
When I add the getter color
below, it doesn't create fromJson
method anymore. I get this error when I run my app:
Error: Method not found: 'Alert.fromJson'.
How come? I thought @JsonKey(ignore: true)
would ignore it? Can I not put methods on JsonSerialzable classes?
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);
}
Upvotes: 2
Views: 1202
Reputation: 3435
json_serializable will generate an implementation of fromJson, but it can't add a factory or static method to your class. You'll have to create the factory yourself (and let the generated implementation do all the real work):
factory Alert.fromJson(Map<String, dynamic> json) => _$AlertFromJson(json);
You may have accidentally deleted that code somehow when you added the color
getter.
Upvotes: 2