I'm working with Flutter and using Freezed for my data types and json deserialization. The database I'm working with will sometimes send the ID element as an int (without quotations) or as a string (with quotations) and I'm looking to set up my Freezed model to be able to handle either and parse it to an int.
Going off of Freezed & json_serializable handling parsing error, I'm trying to use a custom JsonConverter to handle this.
Here's my freezed model:
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';
part 'employee.freezed.dart';
part 'employee.g.dart';
@freezed
class Employee with _$Employee {
const factory Employee({
@StringOrIntToIntConverter String ID,
String name,
String? salutation,
String? fname,
String? lname,
}) = _Employee;
factory Employee.fromJson(Map<String, Object?> json) => _$EmployeeFromJson(json);
}
class StringOrIntToIntConverter implements JsonConverter<int, dynamic> {
const StringOrIntToIntConverter();
@override
int fromJson(dynamic value) {
if (value.runtimeType == int) {
return value as int;
} else {
final valueString = value as String;
return int.parse(valueString);
}
}
@override
int toJson(int value) {
//return int.parse(value);
return value;
}
}
And when I run dart run build_runner build
I get this:
[SEVERE] freezed on lib/data_classes/employee.dart:
Null check operator used on a null value
package:freezed/src/templates/concrete_template.dart 537:46 DefaultValue.defaultValue
package:freezed/src/freezed_generator.dart 178:28 FreezedGenerator._assertValidFreezedConstructorUsage
package:freezed/src/freezed_generator.dart 392:7 FreezedGenerator._parseConstructorsNeedsGeneration
package:freezed/src/freezed_generator.dart 98:47 FreezedGenerator.parseDeclaration
package:freezed/src/parse_generator.dart 56:28 ParserGenerator.generate
package:source_gen/src/builder.dart 342:23 _generate
I've tried simplifying the converter as much as possible (removing the "dynamic" stuff for simplicity's sake) to see if it works, but I always get the same error so I think the issue might be with how I'm using a converter in general here rather than exactly what I'm doing within it.
Is there anything obvious I'm doing wrong here? Alternatively, is there another way I can take either "ID":393
or "ID":"393"
and parse it as an int?
This was embarrassingly simple to fix, @StringOrIntToIntConverter
just needed to be changed to @StringOrIntToIntConverter()
. I overlooked the error telling me to do so since yet-to-be-generated Freezed tiles tend to be full of red underlines that will go away once it's generated.