Skip to content

Instantly share code, notes, and snippets.

@imoyakin
Last active December 21, 2023 02:52
Show Gist options
  • Select an option

  • Save imoyakin/7d910c84aa833e29a7addc3d0891ac74 to your computer and use it in GitHub Desktop.

Select an option

Save imoyakin/7d910c84aa833e29a7addc3d0891ac74 to your computer and use it in GitHub Desktop.
flutter freezed multi version
```dart
abstract class School {
int version = 1;
School();
factory School.fromJson(Map<String, dynamic> json) {
switch (json['version'] as int) {
case 1:
return SchoolEntity1.fromJson(json);
case 2:
return SchoolEntity2.fromJson(json);
default:
throw Exception('Unsupported version: ${json['version']}');
}
}
}
@unfreezed
class SchoolEntity1 extends School with _$SchoolEntity1 {
SchoolEntity1._();
factory SchoolEntity1({
@Default(1) int version,
required String name,
required String teacher,
}) = _SchoolEntity1;
factory SchoolEntity1.fromJson(Map<String, dynamic> json) => _$SchoolEntity1FromJson(json);
}
@unfreezed
class SchoolEntity2 extends School with _$SchoolEntity2 {
SchoolEntity2._();
factory SchoolEntity2({
@Default(2) int version,
required String name,
required String teacher,
@Default("") String principal,
}) = _SchoolEntity2;
factory SchoolEntity2.fromJson(Map<String, dynamic> json) => _$SchoolEntity2FromJson(json);
factory SchoolEntity2.fromSchoolEntity1(SchoolEntity1 entity1) {
return SchoolEntity2(
name: entity1.name,
teacher: entity1.teacher,
);
}
}
```
here the test
```dart
void main() {
group('School', () {
test('should create School instance with correct values', () {
Map<String, dynamic> sj = {
'version': 1,
'name': 'Test School',
'teacher': 'Test Teacher',
};
SchoolEntity1 school1 = SchoolEntity1.fromJson(sj);
expect(school1.version, equals(1));
SchoolEntity2 school2;
school2 = SchoolEntity2.fromSchoolEntity1(school1);
expect(school2.version, equals(2));
});
});
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment