I have a model as below:
// will refer to this as ProfileV1
@freezed
class Profile with _$Profile {
// stands for anon users in firebase auth
const factory Profile.anonymous({
// stands for the id of anon users in firebase auth
required String id,
}) = _AnonymousProfile;
// stands for authed users in firebase auth
const factory Profile.authenticated({
required String id,
required String username,
}) = _AuthenticatedProfile;
factory Profile.fromJson(Map<String, dynamic> json) => _$ProfileFromJson(json);
}
And I work on ProfileV1 for a while, I save some documents with this schema to Firestore. However, a while later, I'd like to introduce a new field to Profile.authenticated
variant as below:
// will refer to this as ProfileV2
@freezed
class Profile with _$Profile {
const factory Profile.anonymous({
required String id,
}) = _AnonymousProfile;
const factory Profile.authenticated({
required String id,
required String username,
// new field, simple for the sake of simplicity
required int upvotes,
}) = _AuthenticatedProfile;
factory Profile.fromJson(Map<String, dynamic> json) => _$ProfileFromJson(json);
}
Now, if I'd like to get the old ProfileV1 documents I've saved in Firestore, Profile.fromJson
of ProfileV2 will probably throw an error saying "There's no upvotes field on the fetched document." of some sort.
How do you deal with this situation? How do you (preferably, lazily) migrate a data schema to another after you fetch it from Firestore?
Environment
- Flutter 3.3.5
- Dart 2.18.2
- Freezed 2.2.0