From 81bb208329f9b7c7c873506f955b45cd4c3fdbaf Mon Sep 17 00:00:00 2001 From: Sebastian Ovide Date: Sun, 16 May 2021 10:59:18 +0100 Subject: [PATCH] added a working inheritance example --- README.md | 1 + _sidebar.md | 1 + custom-objects/inheritance.md | 84 +++++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 custom-objects/inheritance.md diff --git a/README.md b/README.md index f2033e7..cf40e7e 100644 --- a/README.md +++ b/README.md @@ -7,5 +7,6 @@ To contribute, please open pull requests against the master branch. You can run a local preview of the docs by running the following command in the project folder: ``` +npm i docsify-cli -g npx docsify serve ``` \ No newline at end of file diff --git a/_sidebar.md b/_sidebar.md index 8db01f7..6b30e18 100644 --- a/_sidebar.md +++ b/_sidebar.md @@ -13,6 +13,7 @@ - [Generate adapter](custom-objects/generate_adapter.md) - [HiveObject](custom-objects/hive_object.md) - [Relationships](custom-objects/relationships.md) + - [Inheritance](custom-objects/inheritance.md) - [Create adapter manually](custom-objects/create_adapter_manually.md) - Flutter Tutorials diff --git a/custom-objects/inheritance.md b/custom-objects/inheritance.md new file mode 100644 index 0000000..868b887 --- /dev/null +++ b/custom-objects/inheritance.md @@ -0,0 +1,84 @@ +# Inheritance + +Always register the base clase for last. Example + + +```dart +import 'package:hive/hive.dart'; + +part 'models.g.dart'; + +@HiveType(typeId: 0) +class Person extends HiveObject { + @HiveField(0) + List pets = []; + + @HiveField(1) + String name = ""; + + @HiveField(2) + Cat cat = Cat(); + + @HiveField(3) + Dog dog = Dog(); + + Person(); +} + +@HiveType(typeId: 1) +class Pet extends HiveObject { + @HiveField(0) + String name = ""; +} + +@HiveType(typeId: 2) +class Dog extends Pet { + @HiveField(1) + String someDogField = ""; + + Dog() : super(); +} + +@HiveType(typeId: 3) +class Cat extends Pet { + @HiveField(1) + String someCatField = ""; + + Cat() : super(); +} + + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await Hive.initFlutter(); + Hive.registerAdapter(PersonAdapter()); + Hive.registerAdapter(DogAdapter()); + Hive.registerAdapter(CatAdapter()); + Hive.registerAdapter(PetAdapter()); # FOR LAST !!! + + Box boxPersons = await Hive.openBox("persons"); + if (boxPersons.values.isEmpty) { + print("Adding a new person"); + + Person person = Person() + ..name = "person 1" + ..pets = [ + Pet()..name = "pet 1", + Pet()..name = "pet 2", + Pet()..name = "pet 3", + ] + ..dog = (Dog() + ..name = "doggy" + ..someDogField = "waw") + ..cat = (Cat() + ..name = "pussy" + ..someCatField = "meau"); + + boxPersons.put(0, person); + } else { + print(boxPersons.values); + } + + runApp(MyApp()); +} +```