Last active
June 19, 2024 23:23
-
-
Save abdullahalamodi/4b8924a54964c1916bacca0eb11c53e5 to your computer and use it in GitHub Desktop.
restorable custom class
This file contains 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
class TestIt extends StatefulWidget { | |
const TestIt({super.key}); | |
@override | |
State<TestIt> createState() => _TestItState(); | |
} | |
class _TestItState extends State<TestIt> with RestorationMixin { | |
@override | |
Widget build(BuildContext context) { | |
return Container(); | |
} | |
final v = RestorableCustomClass(MyClass(1, 'my name')); | |
@override | |
String? get restorationId => 'test_it_restore_id'; | |
@override | |
void restoreState(RestorationBucket? oldBucket, bool initialRestore) { | |
registerForRestoration(v, 'cutome_class_key'); | |
} | |
} | |
class MyClass { | |
final int id; | |
final String name; | |
MyClass(this.id, this.name); | |
Map<String, dynamic> toMap() { | |
return <String, dynamic>{ | |
'id': id, | |
'name': name, | |
}; | |
} | |
factory MyClass.fromMap(Map<String, dynamic> map) { | |
return MyClass( | |
map['id'] as int, | |
map['name'] as String, | |
); | |
} | |
String toJson() => json.encode(toMap()); | |
factory MyClass.fromJson(String source) => MyClass.fromMap(json.decode(source) as Map<String, dynamic>); | |
} | |
class RestorableCustomClass extends RestorableValue<MyClass> { | |
/// Creates a [RestorableDateTime]. | |
/// | |
/// {@macro flutter.widgets.RestorableNum.constructor} | |
RestorableCustomClass(MyClass defaultValue) : _defaultValue = defaultValue; | |
final MyClass _defaultValue; | |
@override | |
MyClass createDefaultValue() => _defaultValue; | |
@override | |
void didUpdateValue(MyClass? oldValue) { | |
assert(debugIsSerializableForRestoration(value.toJson())); | |
notifyListeners(); | |
} | |
@override | |
MyClass fromPrimitives(Object? data) => MyClass.fromJson(data! as String); | |
@override | |
Object? toPrimitives() => value.toJson(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment