Last active
December 21, 2023 02:52
-
-
Save imoyakin/7d910c84aa833e29a7addc3d0891ac74 to your computer and use it in GitHub Desktop.
flutter freezed multi version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ```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