`
316 | - Support opening boxes from assets
317 |
318 | ### Fixes
319 |
320 | - Fixed bug which was caused by not awaiting write operations
321 | - Fixed bug where custom compaction strategy was not applied
322 | - Hive now locks box files while they are open to prevent concurrent access from multiple processes
323 |
324 | ### More
325 |
326 | - Improved performance of `putAll()`, `deleteAll()`, `add()`, `addAll()`
327 | - Changed `values` parameter of `addAll()` from `List` to `Iterable`
328 | - Improved documentation
329 | - Preparation for queries
330 |
331 | # 1.0.0
332 |
333 | - First stable release
334 |
335 | # 0.5.1+1
336 |
337 | - Change `keys` parameter of `deleteAll` from `List` to `Iterable`
338 | - Fixed bug in `BinaryWriter`
339 |
340 | # 0.5.1
341 |
342 | - Fixed `Hive.init()` bug in browser
343 | - Fixed a bug with large lists or strings
344 | - Improved box opening time in the browser
345 | - Improved general write performance
346 | - Improved docs
347 | - Added integration tests
348 |
349 | # 0.5.0
350 |
351 | - Added `keyComparator` parameter for custom key order
352 | - Added `isEmpty` and `isNotEmpty` getters to box
353 | - Added support for reading and writing subclasses
354 | - Removed length limitation for Lists, Maps, and Strings
355 | - Greatly improved performance of storing Uint8Lists in browser
356 | - Removed CRC check in the browser (not needed)
357 | - Improved documentation
358 | - TypeIds are now allowed in the range of 0-223
359 | - Fixed compaction
360 | - Fixed writing longer Strings
361 | - **Breaking:** Binary format changed
362 |
363 | # 0.4.1+1
364 |
365 | - Document all public APIs
366 | - Fixed flutter_web error
367 |
368 | # 0.4.1
369 |
370 | - Allow different versions of the `path` package
371 |
372 | # 0.4.0
373 |
374 | - Added `BigInt` support
375 | - Added `compactionStrategy` parameter
376 | - Added automatic crash recovery
377 | - Added `add()` and `addAll()` for auto-increment keys
378 | - Added `getAt()`, `putAt()` and `deleteAt()` for working with indices
379 | - Support for int (32 bit unsigned) keys
380 | - Non-lazy boxes now notify their listeners immediately about changes
381 | - Bugfixes
382 | - More tests
383 | - **Breaking:** Open boxes with `openBox()`
384 | - **Breaking:** Writing `null` is no longer equivalent to deleting a key
385 | - **Breaking:** Temporarily removed support for transactions. New API design needed. Will be coming back in a future version.
386 | - **Breaking:** Binary format changed
387 | - **Breaking:** API changes
388 |
389 | # 0.3.0+1
390 |
391 | - Bugfix: `Hive['yourBox']` didn't work with uppercase box names
392 |
393 | # 0.3.0
394 |
395 | - Big step towards stable API
396 | - Support for transactions
397 | - Annotations for hive_generator
398 | - Bugfixes
399 | - Improved web support
400 | - **Breaking:** `inMemory` -> `lazy`
401 | - **Breaking:** Binary format changed
402 |
403 | # 0.2.0
404 |
405 | - Support for dart2js
406 | - Improved performance
407 | - Added `inMemory` option
408 | - **Breaking:** Minor API changes
409 | - **Breaking:** Changed Endianness to little
410 | - **Breaking:** Removed Migrator
411 |
412 | # 0.1.1
413 |
414 | - Downgrade to `meta: ^1.1.6` to support flutter
415 |
416 | # 0.1.0
417 |
418 | - First release
419 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Fast, Enjoyable & Secure NoSQL Database
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | Hive is a lightweight and buzzing-fast key-value database made for Flutter and Dart.
25 |
26 | ## Features 🌟
27 |
28 | - 🌍 Bee everywhere: mobile, desktop, browser
29 | - 🚀 Buzzing speed: Faster than a bee on caffeine!
30 | - 💡 Sweet, powerful, & intuitive API
31 | - 🔐 Queen's Guard: Encryption built right in.
32 | - 🧠 Thinking in swarms: Multi-isolate support.
33 | - 🍯 Everything a bee needs and more!
34 |
35 | > Bee fact: A single bee can visit 5,000 flowers in a day!
36 |
37 | ## Buzz into Action 🐝
38 |
39 | Feeling the excitement? Great! Let's help you take your first flight with Hive.
40 |
41 | #### 🔗 Add dependencies
42 |
43 | To kickstart the journey add `hive`, `isar_flutter_libs` and `path_provider` to your `pubspec.yaml`.
44 |
45 | ```yaml
46 | dependencies:
47 | hive: ^4.0.0
48 | isar_flutter_libs: ^4.0.0-dev.13
49 | path_provider: ^2.1.0
50 | ```
51 |
52 | Pssst! 🤫 `path_provider` will help you to find the optimal directory for each platform.
53 |
54 | #### 🏡 Designate a Home
55 |
56 | Hive needs a place to call home. Using `path_provider` we can find a valid directory.
57 |
58 | ```dart
59 | void main() async {
60 | WidgetsFlutterBinding.ensureInitialized();
61 | final dir = await getApplicationDocumentsDirectory();
62 | Hive.defaultDirectory = dir.path;
63 |
64 | // ...
65 | }
66 | ```
67 |
68 | #### 🏁 And... Action!
69 |
70 | Woohoo! You're all set. Jump in and let your Hive adventure begin!
71 |
72 | ```dart
73 | import 'package:hive/hive.dart';
74 |
75 | final box = Hive.box();
76 | box.put('name', 'David');
77 |
78 | final name = box.get('name');
79 | print('Name: $name');
80 | ```
81 |
82 | > Bee fact: Honeybees can fly at a speed of up to 30 kilometers per hour!
83 |
84 | # 📚 Hive Handbook
85 |
86 | In Hive, data is neatly organized into containers known as boxes. Think of boxes as tables you'd find in SQL, but far more flexible — they don't stick to a set structure and can contain a variety of data. Boxes can be encrypted to store sensitive data.
87 |
88 | ## Table of Contents
89 |
90 | Want to jump to a specific section? Here's a handy table of contents:
91 |
92 | - [Opening Boxes](#-opening-boxes)
93 | - [Closing Boxes](#-bidding-adieu-closing-boxes)
94 | - [Inserting](#-filling-the-honeycomb-inserting-data)
95 | - [Reading](#-extracting-honey-i-mean-data)
96 | - [Deleting](#-deleting-data)
97 | - [Using Boxes like Lists](#-using-boxes-like-lists)
98 | - [Type safety](#-type-safety)
99 | - [Non-primitive Objects](#-bee-yond-the-basics-non-primitive-objects)
100 | - [Transactions](#-transactions)
101 | - [Isolates](#-the-isolate-dance)
102 | - [FAQ](#-buzzworthy-questions)
103 |
104 | > Bee fact: Bees have five eyes – three simple eyes on top of the head, and two compound eyes, with numerous hexagonal facets.
105 |
106 | ### 📦 Opening Boxes
107 |
108 | Your journey with Hive begins with opening your first box. Trust me, it's unbee-lievably easy:
109 |
110 | ```dart
111 | final box = Hive.box(name: 'myBox');
112 | ```
113 |
114 | When you call `Hive.box(name: 'myBox')` for the first time with a given name, Hive will create a new box for you. If you call it again with the same name, Hive will return the already existing box.
115 |
116 | You can also use `Hive.box()` without providing a name. In this case, Hive will return the default box.
117 |
118 | There are optional parameters you can pass to `Hive.box()`:
119 |
120 | | Parameter | Description |
121 | | --------------- | ------------------------------------------------------------------------- |
122 | | `name` | Label your box with a distinct name |
123 | | `directory` | Select a home for your box. If omitted, Hive uses the `defaultDirectory`. |
124 | | `encryptionKey` | Hand over this key, and Hive will encrypt your box. Keep it safe! |
125 | | `maxSizeMiB` | The maximum size of the box in MiB. Go for a modest number. |
126 |
127 | > Bee fact: Beeswax, which is secreted from the abdomen of worker bees, is used to construct the honeycomb.
128 |
129 | ### 🌂 Bidding Adieu: Closing Boxes
130 |
131 | It's not advised to close boxes that might be accessed again. This prevents unnecessary overhead of reopening the box and ensures smooth data retrieval.
132 |
133 | To close a box just call `box.close()`. Wipe the box from the face of the earth with `box.deleteFromDisk()`.
134 |
135 | > Bee fact: When a bee finds a good source of nectar, it flies back to the hive and shows its friends where the nectar source is by doing a dance.
136 |
137 | ### ✍️ Filling the Honeycomb: Inserting Data
138 |
139 | Once we have a box, it's time to fill it with sweet data! At its core, a box is just a key-value store. String keys are mapped to arbitrary primitive values. You can think of a box as a persisted `Map`.
140 |
141 | ```dart
142 | final box = Hive.box();
143 | box.put('danceMoves', 'Waggle Dance');
144 | box.put('wingSpeed', 200);
145 | ```
146 |
147 | Updating values? If a particular key already exists, Hive simply updates its corresponding value. And complex types like lists and maps? They're in too!
148 |
149 | ```dart
150 | box.put('friends', ['Buzzy', 'Stinger', 'Honey']);
151 | box.put('memories', {'firstFlight': 'Sunny Day', 'bestNectar': 'Rose'});
152 | ```
153 |
154 | Instead of `.put()` you prefer the syntax of maps? Hive gets you:
155 |
156 | ```dart
157 | box['danceMoves'] = 'Round Dance';
158 | box['wingSpeed'] = 220;
159 | ```
160 |
161 | Got a bucket of honey facts? Drop them all at once with `box.putAll()`:
162 |
163 | ```dart
164 | box.putAll({'favoriteFlower': 'Lavender', 'wingSpeed': 210});
165 | ```
166 |
167 | > Bee fact: A single bee colony can produce anywhere from 30 to 100 pounds of honey in a year, depending on the availability of nectar sources.
168 |
169 | ### 👀 Extracting Honey... I mean, Data!
170 |
171 | Need a snippet of info from your Hive? No need to don the beekeeper suit; just scoop it out using `box.get()` or `box.getAll()`. If a key doesn't exist, `box.get()` simply return a `null`. But fret not; you can tell it to have a backup plan:
172 |
173 | ```dart
174 | final box = Hive.box(name: 'beeees');
175 | final fav = box.get('favoriteFlower');
176 | final moves = box.get('danceMoves', defaultValue: 'waggle');
177 | ```
178 |
179 | Oh, and if you're feeling fancy, use the `[]` operator for a more stylish approach:
180 |
181 | ```dart
182 | final fav = box['favoriteFlower'];
183 | final moves = box['danceMoves'] ?? 'waggle';
184 | ```
185 |
186 | > Bee fact: Worker bees are the only bees most people ever see flying around outside the hive. They're female, and their roles are to forage for food, build and protect the hive, and more.
187 |
188 | ### 🧹 Deleting Data
189 |
190 | Time for some spring cleaning in the hive! To remove a single entry from your box, use `box.delete()`:
191 |
192 | ```dart
193 | final deleted = box.delete('lavenderHoney');
194 | print('Honey eaten: $deleted'); // Honey eaten: true
195 | ```
196 |
197 | Perhaps it's time for a complete reset, making space for a fresh batch of honey. If you're looking to remove all key-value pairs from a box, use `box.clear()`:
198 |
199 | ```dart
200 | box.clear();
201 | ```
202 |
203 | > Bee fact: Bees have been around for more than 30 million years! Their long history predates the existence of humans and even dinosaurs.
204 |
205 | ### ✨ Using Boxes like Lists
206 |
207 | In the bee world, honeycombs aren't just random compartments; they're methodically organized. Similarly, while we've been viewing Hive boxes as maps so far, they can be used just like lists:
208 |
209 | ```dart
210 | final box = Hive.box();
211 |
212 | box.add('Rose');
213 | box.add('Tulip');
214 |
215 | print(box.getAt(0)); // Rose
216 | print(box.getAt(1)); // Tulip
217 | ```
218 |
219 | But remember, bees can't retrieve honey from a comb that's empty or doesn't exist. Likewise, index-based operations will throw an error if you try an index out of bounds:
220 |
221 | ```dart
222 | final box = Hive.box();
223 | box.add('Daisy');
224 | print(box.getAt(1)); // Error! This will make the bees buzz in confusion
225 | ```
226 |
227 | Even if we insert a key-value pair we can still access the values by index.
228 |
229 | ```dart
230 | final box = Hive.box();
231 |
232 | box.add('Lily');
233 | box.put('key', 'Orchid');
234 |
235 | print(box.getAt(0)); // Lily
236 | print(box.getAt(1)); // Orchid
237 | ```
238 |
239 | Of course, we can also use the `[]` operator in combination with indexes :
240 |
241 | ```dart
242 | final box = Hive.box();
243 |
244 | box.add('Marigold');
245 | print(box[0]); // Marigold
246 |
247 | box[0] = 'Daffodil';
248 | box[1] = 'Bluebell'; // Error! This will get the bees in a whirl
249 | ```
250 |
251 | > Bee fact: To produce one pound of honey, a hive's bees must visit 2 million flowers and fly over 55,000 miles.
252 |
253 | ### 🛡️ Type safety
254 |
255 | Safety is the bee's priority! To keep your data sweet and pure boxes have an optional generic type parameter. It allows you to store only values of a specific type in a box:
256 |
257 | ```dart
258 | final box = Hive.box(name: 'BeeTreasures');
259 | box.put('DaisyDance', 'SweetNectarShake');
260 | box.put('RoseRumba', 'GoldenPollenParty');
261 | box.put('TulipTango', 777); // Error - You can't fool the bees!
262 | ```
263 |
264 | Make sure to use the same type whenever you get the box. Otherwise, you'll get an error:
265 |
266 | ```dart
267 | Hive.box(name: 'BeeTreasures'); // Error - We already have a String box!
268 | ```
269 |
270 | > Bee fact: Bees have two stomachs. One is for eating, and the other is for storing nectar collected from flowers or water so they can carry it back to their hive. Talk about a sweet backpack!
271 |
272 | ### 🧩 Bee-yond the Basics: Non-primitive Objects
273 |
274 | Hive goes beyond storing just basic data types! Along with primitives, lists, and maps, Hive can store any Dart object of your liking. The only buzz you need to know? Your object should come equipped with a `.fromJson()` and `.toJson()` method:
275 |
276 | ```dart
277 | class Bee {
278 | Bee({required this.name, required this.role});
279 |
280 | factory Bee.fromJson(Map json) => Bee(
281 | name: json['name'] as String,
282 | role: json['role'] as String,
283 | );
284 |
285 | final String name;
286 | final String role;
287 |
288 | Map toJson() => {
289 | 'name': name,
290 | 'role': role,
291 | };
292 | }
293 | ```
294 |
295 | Before our bee-friends can buzz around in Hive, you need to do the beekeeper's job and register the `Bee` class:
296 |
297 | ```dart
298 | Hive.registerAdapter('Bee', Bee.fromJson);
299 | ```
300 |
301 | Now, you're all set to let your bees fly:
302 |
303 | ```dart
304 | final box = Hive.box();
305 |
306 | final bumble = Bee(name: 'Bumble', role: 'Worker');
307 | box.put('BumbleID', bumble);
308 |
309 | print(box.get('BumbleID')); // Bumble - Worker
310 | ```
311 |
312 | > Bee fact: Bees are responsible for pollinating about one-third of the world's food crops.
313 |
314 | ### 🪢 Transactions
315 |
316 | Transactions are an efficient way to update multiple values at once. They are also useful if you want to make sure that a Box is not changed by other code while you are working with it.
317 |
318 | ```dart
319 | final box = Hive.box();
320 |
321 | box.write(() {
322 | box.store('nectar1', 'GoldenNectar');
323 | box.store('nectar2', 'WildflowerBrew');
324 | box.store('nectar3', 'CloverDew');
325 | });
326 |
327 | box.read(() {
328 | box.get('nectar1'); // GoldenNectar
329 | });
330 | ```
331 |
332 | Changes made in a transaction are always atomic. Either all changes are applied or none of them. So if an error occurs during a transaction, the box will not be changed.
333 |
334 | ```dart
335 | final box = Hive.box();
336 | box.put('honeyLevel', 5);
337 |
338 | box.write(() {
339 | box.put('honeyLevel', 6);
340 | throw Exception('Oh no!!!');
341 | });
342 |
343 | print(box.get('honeyLevel')); // 5
344 | ```
345 |
346 | > Bee fact: Bees can recognize human faces, and they can even be trained to associate a picture of a face with sweet treats!
347 |
348 | ### 💃 The Isolate Dance
349 |
350 | Just like a beehive where multiple bees work simultaneously, you can buzz into Hive from various Isolates at the same time. This nifty trick is great when you wish to keep those database activities separate from your UI thread.
351 |
352 | Hive comes with a sweet `Hive.compute()` method that runs a function in a different isolate. The best part? It also does the honey-making job of setting up and tidying resources for you.
353 |
354 | ```dart
355 | // Opening the bee's box
356 | final box = Hive.box();
357 |
358 | // Storing some sweet nectar
359 | box.put('nectarType', 'wildflower');
360 |
361 | await Hive.compute(() {
362 | // Accessing the same box from another worker bee
363 | final box = Hive.box();
364 | print(box.get('nectarType')); // wildflower
365 |
366 | // Updating the nectar's quality
367 | box.put('nectarType', 'lavender');
368 | });
369 |
370 | // Tasting the updated honey flavor
371 | print(honeycomb.get('nectarType')); // lavender
372 | ```
373 |
374 | Just remember, while the bees dance in harmony, ensure your Isolates do too! 🐝🎶
375 |
376 | > Bee fact: Bees have two pairs of wings, and they beat 11,400 times per minute.
377 |
378 | ### 🍯 Buzzworthy Questions
379 |
380 | #### 🐝 To bee or not to bee: Hive or Isar?
381 |
382 | > It's not always black and yellow! 🖤💛 Both Hive and Isar have their sweet spots. Hive is a lightweight wrapper around Isar so if you are looking for a simple key-value store, Hive might be enough. Isar is the way to go if you need queries, relations, and more advanced features.
383 |
384 | #### 🚀 Will using Hive make my app as fast as a bee?
385 |
386 | > While we can't promise your app will gain wings, 🦋 Hive sure will give it the speed it deserves. Hive is very resource efficient and optimized for mobile devices. Flutter like a butterfly, sting like a bee! 🐝
387 |
388 | #### 🗂 Where in the beehive does Hive hide my honey... I mean, data?
389 |
390 | > Remember the `defaultDirectory` we set at the beginning? 📍 That's where Hive stores your data in a file named `yourBoxName.isar` or `yourBoxName.sqlite`.
391 |
392 | #### 📸 I've got some bee-autiful images! Can I store them directly in Hive?
393 |
394 | > While you might be tempted to put those pics right into Hive, 🖼️ it's best to store your images and other binary data as files outside Hive. You can then store the file path in Hive. Think of it like leaving honey out in the open; it's better to keep it neatly stored in the appropriate place. 🏺
395 |
396 | #### 😲 Yikes! What if my app meets an untimely demise (gets killed)? What becomes of my Hive?
397 |
398 | > No need for a bee-mergency! 🚨 If your app buzzes off unexpectedly, Hive ensures that your data remains safe and sound. Transactions are atomic, so either all changes are applied or none of them. If an error occurs during a transaction, the box will not be changed.
399 |
400 | #### 🔐 How does Hive keep our data safe from sticky fingers?
401 |
402 | > We've got the queen's guard on duty! 🛡️ If you encrypt your box Hive uses 256-bit AES in CBC mode. Every database page is safeguarded separately, ensuring your sweet stuff remains secure and only accessible to those with the right key. Buzz-worthy protection, right? 🗝️
403 |
404 | #### 🤝 When should I rally the troops and use transactions?
405 |
406 | > Just like a hive making big decisions together, 🌐 you'll want to use transactions when you have several operations that should be executed together. If one fails, they all fail. It ensures your data stays consistent, safe, and buzzing in harmony! 🎶
407 |
408 | #### 🤣 What if I'm allergic to bees?
409 |
410 | > No worries! Hive is 100% sting-free, 🚫 although we're pretty sure you'll get a buzz out of its performance.
411 |
412 | #### ⏳ Hive operations are synchronous. Doesn't that make the bee waltz a bit slow?
413 |
414 | > Hive is incredibly fast and efficient. 🚄 It's built on top of Isar, a high-performance database engine. If you want to keep database operations away from your UI isolate, you can use `compute()` or `Isolate.run()` to run them in a separate isolate.
415 |
416 | #### 📦 How many boxes should a wise beekeeper have?
417 |
418 | > While the sky's the limit in the world of bees, 🌌 in Hive, every box becomes a separate file. So, even if you're buzzing with excitement, it's wise not to overdo it. 📚
419 |
420 | ### 📜 License
421 |
422 | ```
423 | Copyright 2023 Simon Choi
424 |
425 | Licensed under the Apache License, Version 2.0 (the "License");
426 | you may not use this file except in compliance with the License.
427 | You may obtain a copy of the License at
428 |
429 | http://www.apache.org/licenses/LICENSE-2.0
430 |
431 | Unless required by applicable law or agreed to in writing, software
432 | distributed under the License is distributed on an "AS IS" BASIS,
433 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
434 | See the License for the specific language governing permissions and
435 | limitations under the License.
436 | ```
437 |
--------------------------------------------------------------------------------
/analysis_options.yaml:
--------------------------------------------------------------------------------
1 | include: package:very_good_analysis/analysis_options.yaml
2 | analyzer:
3 | exclude:
4 | - "**/*.g.dart"
5 |
6 | linter:
7 | rules:
8 | cascade_invocations: false
9 | use_string_in_part_of_directives: false
10 | always_put_required_named_parameters_first: false
11 | use_setters_to_change_properties: false
12 |
--------------------------------------------------------------------------------
/example/README.md:
--------------------------------------------------------------------------------
1 | ## 🌼 Welcome, Beekeeper! 🐝
2 |
3 | Let's embark on a buzzworthy journey into the world of Flutter and Dart using Hive! Ready to see Hive in action? This example will walk you through setting up a Flutter project and implementing Hive to store data on a list of favorite flowers for bees.
4 |
5 | ## 🌺 Buzzy Beginnings
6 |
7 | Create a new Flutter app:
8 |
9 | ```bash
10 | flutter create bee_favorites
11 | cd bee_favorites
12 | ```
13 |
14 | Now we can add some sweet dependencies to our `pubspec.yaml`:
15 |
16 | ```yaml
17 | dependencies:
18 | flutter:
19 | sdk: flutter
20 | hive: ^4.0.0
21 | isar_flutter_libs: ^4.0.0-dev.13
22 | path_provider: ^2.0.0
23 | ```
24 |
25 | ## 🌻 Setting up Hive
26 |
27 | Before we get into the code, let's set up Hive:
28 |
29 | ```dart
30 | import 'package:flutter/material.dart';
31 | import 'package:hive/hive.dart';
32 | import 'package:path_provider/path_provider.dart';
33 |
34 | void main() async {
35 | WidgetsFlutterBinding.ensureInitialized();
36 |
37 | final directory = await getApplicationDocumentsDirectory();
38 | Hive.defaultDirectory = directory.path;
39 |
40 | runApp(BeeApp());
41 | }
42 | ```
43 |
44 | ## 🌸 Bee Favorites App
45 |
46 | Let's build a simple Flutter app where bees can vote for their favorite flowers!
47 |
48 | ```dart
49 | class BeeApp extends StatelessWidget {
50 | @override
51 | Widget build(BuildContext context) {
52 | return MaterialApp(
53 | title: 'Bee Favorites',
54 | theme: ThemeData(primarySwatch: Colors.yellow),
55 | home: FavoriteFlowers(),
56 | );
57 | }
58 | }
59 |
60 | class FavoriteFlowers extends StatefulWidget {
61 | @override
62 | _FavoriteFlowersState createState() => _FavoriteFlowersState();
63 | }
64 |
65 | class _FavoriteFlowersState extends State {
66 | final Box favoriteBox = Hive.box('favorites');
67 |
68 | final List flowers = ['Rose', 'Tulip', 'Daisy', 'Lily', 'Sunflower'];
69 |
70 | @override
71 | Widget build(BuildContext context) {
72 | return Scaffold(
73 | appBar: AppBar(title: Text('Bee Favorites 🐝')),
74 | body: ListView.builder(
75 | itemCount: flowers.length,
76 | itemBuilder: (context, index) {
77 | final flower = flowers[index];
78 | return ListTile(
79 | title: Text(flower),
80 | trailing: IconButton(
81 | icon: Icon(Icons.star),
82 | onPressed: () {
83 | favoriteBox.add(flower);
84 | ScaffoldMessenger.of(context).showSnackBar(
85 | SnackBar(content: Text('$flower added to favorites! 🌼')),
86 | );
87 | },
88 | ),
89 | );
90 | },
91 | ),
92 | floatingActionButton: FloatingActionButton(
93 | child: Icon(Icons.view_list),
94 | onPressed: () {
95 | showDialog(
96 | context: context,
97 | builder: (context) => FavoritesDialog(favorites: favoriteBox.values.toList()),
98 | );
99 | },
100 | ),
101 | );
102 | }
103 | }
104 |
105 | class FavoritesDialog extends StatelessWidget {
106 | final List favorites;
107 |
108 | FavoritesDialog({required this.favorites});
109 |
110 | @override
111 | Widget build(BuildContext context) {
112 | return AlertDialog(
113 | title: Text('Bee Favorites 🌼'),
114 | content: Container(
115 | width: 300,
116 | height: 200,
117 | child: ListView.builder(
118 | itemCount: favorites.length,
119 | itemBuilder: (context, index) {
120 | return ListTile(title: Text(favorites[index]));
121 | },
122 | ),
123 | ),
124 | actions: [
125 | TextButton(
126 | child: Text('Close'),
127 | onPressed: () => Navigator.of(context).pop(),
128 | ),
129 | ],
130 | );
131 | }
132 | }
133 | ```
134 |
135 | ## 🐝 Bee-fore You Go...
136 |
137 | Once you've completed this tutorial, run your app! Every time a bee (or user) selects a flower, it's added to the favorites list, and you can view the favorites with the FloatingActionButton!
138 |
139 | > **Bee fact:** Bees communicate through a combination of chemical scents and movements. One known movement is the waggle dance, which indicates the location of a food source!
140 |
141 | Check out the full documentation in Hive's readme and the other example apps.
142 |
--------------------------------------------------------------------------------
/lib/hive.dart:
--------------------------------------------------------------------------------
1 | /// Hive is a lightweight and blazing fast key-value store made for Flutter and
2 | /// Dart. It is strongly encrypted using AES-256.
3 | library hive;
4 |
5 | import 'dart:async';
6 | import 'dart:isolate'
7 | if (dart.library.html) 'package:hive/src/impl/isolate_stub.dart';
8 |
9 | import 'package:hive/src/impl/frame.dart';
10 | import 'package:isar/isar.dart';
11 |
12 | part 'src/impl/box_impl.dart';
13 | part 'src/impl/type_registry.dart';
14 | part 'src/box.dart';
15 | part 'src/hive.dart';
16 |
--------------------------------------------------------------------------------
/lib/src/box.dart:
--------------------------------------------------------------------------------
1 | part of hive;
2 |
3 | /// A box contains and manages a collection of key-value pairs.
4 | @pragma('vm:isolate-unsendable')
5 | abstract interface class Box {
6 | /// Whether this box is currently open.
7 | ///
8 | /// Most of the operations on a box require it to be open.
9 | bool get isOpen;
10 |
11 | /// The name of the box.
12 | String get name;
13 |
14 | /// The location of the box in the file system. In the browser, this is null.
15 | String? get directory;
16 |
17 | /// The number of entries in the box.
18 | int get length;
19 |
20 | /// Whether the box is empty.
21 | bool get isEmpty;
22 |
23 | /// Whether the box is not empty.
24 | bool get isNotEmpty;
25 |
26 | /// Start a read transaction on the box.
27 | ///
28 | /// Transactions provides and atomic view on the box. All read operations
29 | /// inside the transaction will see the same state of the box.
30 | T read(T Function() callback);
31 |
32 | /// Start a write transaction on the box.
33 | ///
34 | /// Transactions provides and atomic view on the box. All read operations
35 | /// inside the transaction will see the same state of the box.
36 | T write(T Function() callback);
37 |
38 | /// All the keys in the box.
39 | ///
40 | /// The keys are sorted by their insertion order.
41 | List get keys;
42 |
43 | /// Get the n-th key in the box.
44 | String? keyAt(int index);
45 |
46 | /// Checks whether the box contains the [key].
47 | bool containsKey(String key);
48 |
49 | // Returns the value associated with the given [key]. If the key does not
50 | /// exist, `null` is returned.
51 | ///
52 | /// If [defaultValue] is specified, it is returned in case the key does not
53 | /// exist.
54 | E? get(String key, {E? defaultValue});
55 |
56 | /// Returns the value associated with the n-th key.
57 | E getAt(int index);
58 |
59 | /// Returns the value associated with the given [key]. The key can either be
60 | /// a [String] or an [int] to get an entry by its index.
61 | E? operator [](Object key);
62 |
63 | /// Returns all values associated with the given [keys] or `null` if a key
64 | /// does not exist.
65 | List getAll(Iterable keys);
66 |
67 | /// Returns all values in the given range.
68 | ///
69 | /// Throws a [RangeError] if [start] or [end] are out of bounds.
70 | List getRange(int start, int end);
71 |
72 | /// Returns all values between [startKey] and [endKey] (inclusive).
73 | List getBetween({String? startKey, String? endKey});
74 |
75 | /// Saves the [key] - [value] pair.
76 | void put(String key, E value);
77 |
78 | /// Associates the [value] with the n-th key. An exception is raised if the
79 | /// key does not exist.
80 | void putAt(int index, E value);
81 |
82 | /// Saves the [key] - [value] pair. The key can either be a [String] or an
83 | /// [int] to save an entry by its index.
84 | void operator []=(Object key, E value);
85 |
86 | /// Saves all the key - value pairs in the [entries] map.
87 | void putAll(Map entries);
88 |
89 | /// Overwrites the values in the given range with the given [values].
90 | void putRange(int start, int end, Iterable values);
91 |
92 | /// Saves the [value] with an auto-increment key.
93 | void add(E value);
94 |
95 | /// Saves all the [values] with auto-increment keys.
96 | void addAll(Iterable values);
97 |
98 | /// Deletes the given [key] from the box.
99 | ///
100 | /// If it does not exist, nothing happens.
101 | bool delete(String key);
102 |
103 | /// Deletes the n-th key from the box.
104 | ///
105 | /// If it does not exist, nothing happens.
106 | void deleteAt(int index);
107 |
108 | /// Deletes all the given [keys] from the box.
109 | ///
110 | /// If a key does not exist, it is skipped.
111 | int deleteAll(Iterable keys);
112 |
113 | /// Deletes all the entries in the given range.
114 | void deleteRange(int start, int end);
115 |
116 | /// Removes all entries from the box.
117 | void clear({bool notify = true});
118 |
119 | /// Closes the box.
120 | ///
121 | /// Be careful, this closes all instances of this box. You have to make sure
122 | /// that you don't access the box anywhere else after that.
123 | void close();
124 |
125 | /// Removes the file which contains the box and closes the box.
126 | ///
127 | /// If a box is still open in another isolate, it will not be deleted.
128 | void deleteFromDisk();
129 |
130 | /// Watch for changes to the given [key].
131 | Stream watchKey(String key);
132 |
133 | /// Returns a broadcast stream of all changes to the box. This should mainly
134 | /// be used to be notified of changes in background isolates.
135 | Stream watch();
136 | }
137 |
--------------------------------------------------------------------------------
/lib/src/hive.dart:
--------------------------------------------------------------------------------
1 | part of hive;
2 |
3 | /// Open boxes and register adapters.
4 | class Hive {
5 | static var _typeRegistry = _TypeRegistry();
6 | static final _openBoxes = >{};
7 |
8 | /// The default name if you don't specify a name for a box.
9 | static const defaultName = 'hive';
10 |
11 | /// The default directory for all boxes.
12 | static String? defaultDirectory;
13 |
14 | /// Registers a type adapter to allow Hive to (de)serialize your objects.
15 | ///
16 | /// Example:
17 | /// ```dart
18 | /// class Person {
19 | /// String name;
20 | /// int age;
21 | ///
22 | /// factory Person.fromJson(Map json) {
23 | /// return Person()
24 | /// ..name = json['name'] as String
25 | /// ..age = json['age'] as int;
26 | /// }
27 | ///
28 | /// Map toJson() {
29 | /// return {
30 | /// 'name': name,
31 | /// 'age': age,
32 | /// };
33 | /// }
34 | /// }
35 | ///
36 | /// Hive.registerAdapter('Person', Person.fromJson);
37 | /// ```
38 | static void registerAdapter(
39 | String typeName,
40 | T? Function(dynamic json) fromJson,
41 | ) {
42 | _typeRegistry.register(Isar.fastHash(typeName), fromJson);
43 | }
44 |
45 | /// Get or open the box with [name] in the given [directory]. If no directory
46 | /// is specified, the default directory is used.
47 | ///
48 | /// If the box is already open, the same instance is returned.
49 | ///
50 | /// The [encryptionKey] is used to encrypt the box. If the box was already
51 | /// opened with a different encryption key, an error is thrown.
52 | ///
53 | /// The [maxSizeMiB] is the maximum size of the box in MiB. If the box grows
54 | /// bigger than this, an exception is thrown. It is recommended to set this
55 | /// value to a small value if possible.
56 | static Box box({
57 | String name = defaultName,
58 | String? directory,
59 | String? encryptionKey,
60 | int maxSizeMiB = 5,
61 | }) {
62 | final box = _openBoxes[name];
63 | if (box != null) {
64 | if (box is Box) {
65 | return box;
66 | } else {
67 | throw ArgumentError('Box was already opened with a different type. '
68 | 'Expected Box<${box.runtimeType}> but got Box<$E>.');
69 | }
70 | }
71 |
72 | final dir = directory ?? defaultDirectory;
73 | if (dir == null) {
74 | throw ArgumentError(
75 | 'No directory specified and no default directory set.',
76 | 'directory',
77 | );
78 | }
79 |
80 | final isar = Isar.open(
81 | name: name,
82 | schemas: [FrameSchema],
83 | directory: dir,
84 | engine: encryptionKey != null ? IsarEngine.sqlite : IsarEngine.isar,
85 | maxSizeMiB: maxSizeMiB,
86 | encryptionKey: encryptionKey,
87 | inspector: false,
88 | );
89 | final newBox = _BoxImpl(isar);
90 | _openBoxes[name] = newBox;
91 | return newBox;
92 | }
93 |
94 | /// Runs [computation] in a new isolate and returns the result. Also takes
95 | /// care of initializing Hive and closing all boxes afterwards.
96 | ///
97 | /// The optional [debugName] can be used to identify the isolate in debuggers.
98 | static Future compute(
99 | FutureOr Function() computation, {
100 | String? debugName,
101 | }) {
102 | final registry = _typeRegistry;
103 | final dir = defaultDirectory;
104 | return Isolate.run(
105 | () async {
106 | Hive._typeRegistry = registry;
107 | Hive.defaultDirectory = dir;
108 | try {
109 | return await computation();
110 | } finally {
111 | Hive.closeAllBoxes();
112 | }
113 | },
114 | debugName: debugName ?? 'Hive Isolate',
115 | );
116 | }
117 |
118 | /// Closes all open boxes.
119 | static void closeAllBoxes() {
120 | for (final box in _openBoxes.values) {
121 | box.close();
122 | }
123 | }
124 |
125 | /// Closes all open boxes and delete their data.
126 | ///
127 | /// If a box is still open in another isolate, it will not be deleted.
128 | static void deleteAllBoxesFromDisk() {
129 | for (final box in _openBoxes.values) {
130 | box.deleteFromDisk();
131 | }
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/lib/src/impl/box_impl.dart:
--------------------------------------------------------------------------------
1 | part of hive;
2 |
3 | class _BoxImpl implements Box {
4 | _BoxImpl(this.isar) : collection = isar.frames;
5 |
6 | final Isar isar;
7 | final IsarCollection collection;
8 |
9 | bool? writeTxn;
10 |
11 | @override
12 | bool get isOpen => isar.isOpen;
13 |
14 | @override
15 | String get name => isar.name;
16 |
17 | @override
18 | String get directory => isar.directory;
19 |
20 | @override
21 | int get length => collection.count();
22 |
23 | @override
24 | bool get isEmpty => length == 0;
25 |
26 | @override
27 | bool get isNotEmpty => length != 0;
28 |
29 | @override
30 | T read(T Function() callback) {
31 | if (writeTxn == null) {
32 | return isar.read((isar) {
33 | writeTxn = false;
34 | try {
35 | return callback();
36 | } finally {
37 | writeTxn = null;
38 | }
39 | });
40 | } else {
41 | return callback();
42 | }
43 | }
44 |
45 | @override
46 | T write(T Function() callback) {
47 | if (writeTxn == null) {
48 | return isar.write((isar) {
49 | writeTxn = true;
50 | try {
51 | return callback();
52 | } finally {
53 | writeTxn = null;
54 | }
55 | });
56 | } else if (writeTxn!) {
57 | return callback();
58 | } else {
59 | throw StateError('Cannot write inside a read transaction.');
60 | }
61 | }
62 |
63 | @override
64 | List get keys {
65 | return collection.where().keyIsNotNull().keyProperty().findAll().cast();
66 | }
67 |
68 | @override
69 | String? keyAt(int index) {
70 | final frame = collection.where().findFirst(offset: index);
71 |
72 | if (frame == null) {
73 | throw IndexError.withLength(index, length);
74 | }
75 |
76 | return frame.key;
77 | }
78 |
79 | E _frameFromJson(Frame frame) {
80 | return Hive._typeRegistry.fromJson(frame.typeId, frame.value);
81 | }
82 |
83 | @override
84 | bool containsKey(String key) {
85 | return !collection.where().keyEqualTo(key).isEmpty();
86 | }
87 |
88 | @override
89 | E? get(String key, {E? defaultValue}) {
90 | final frame = collection.where().keyEqualTo(key).findFirst();
91 | return frame != null ? _frameFromJson(frame) : defaultValue;
92 | }
93 |
94 | @override
95 | E getAt(int index) {
96 | final frame = collection.where().findFirst(offset: index);
97 |
98 | if (frame == null) {
99 | throw IndexError.withLength(index, length);
100 | }
101 |
102 | return _frameFromJson(frame);
103 | }
104 |
105 | @override
106 | E? operator [](dynamic key) {
107 | if (key is int) {
108 | return getAt(key);
109 | } else if (key is String) {
110 | return get(key);
111 | } else {
112 | throw ArgumentError.value(key, 'key', 'must be a String or int');
113 | }
114 | }
115 |
116 | @override
117 | List getAll(Iterable keys) {
118 | if (keys.isEmpty) return [];
119 |
120 | final frames = collection
121 | .where()
122 | // ignore: inference_failure_on_function_invocation
123 | .anyOf(
124 | keys,
125 | (q, key) => q.keyEqualTo(key),
126 | )
127 | .findAll();
128 |
129 | return frames.map(_frameFromJson).toList();
130 | }
131 |
132 | @override
133 | List getRange(int start, int end) {
134 | if (start == 0 && end == 0) {
135 | return [];
136 | }
137 |
138 | final frames = collection
139 | .where()
140 | .findAll(offset: start, limit: end - start)
141 | .map(_frameFromJson)
142 | .toList();
143 |
144 | if (frames.length != end - start) {
145 | RangeError.checkValidRange(start, end, length);
146 | }
147 |
148 | return frames;
149 | }
150 |
151 | @override
152 | List getBetween({String? startKey, String? endKey}) {
153 | final frames = collection
154 | .where()
155 | .optional(
156 | endKey != null,
157 | (q) => q.keyBetween(startKey ?? '', endKey),
158 | )
159 | .optional(
160 | endKey == null,
161 | (q) => q.keyGreaterThanOrEqualTo(startKey ?? ''),
162 | )
163 | .findAll()
164 | .map(_frameFromJson)
165 | .toList();
166 |
167 | return frames;
168 | }
169 |
170 | @override
171 | void put(String key, E value) {
172 | write(() {
173 | final frame = Frame(
174 | id: collection.autoIncrement(),
175 | typeId: Hive._typeRegistry.findTypeId(value),
176 | key: key,
177 | value: value,
178 | );
179 | collection.put(frame);
180 | });
181 | }
182 |
183 | @override
184 | void putAt(int index, E value) {
185 | write(() {
186 | final idAtIndex =
187 | collection.where().idProperty().findFirst(offset: index);
188 | if (idAtIndex == null) {
189 | throw IndexError.withLength(index, length);
190 | }
191 |
192 | final frame = Frame(
193 | id: idAtIndex,
194 | typeId: Hive._typeRegistry.findTypeId(value),
195 | value: value,
196 | );
197 | collection.put(frame);
198 | });
199 | }
200 |
201 | @override
202 | void operator []=(Object key, E value) {
203 | if (key is int) {
204 | putAt(key, value);
205 | } else if (key is String) {
206 | put(key, value);
207 | } else {
208 | throw ArgumentError.value(key, 'key', 'must be a String or int');
209 | }
210 | }
211 |
212 | @override
213 | void putAll(Map entries) {
214 | write(() {
215 | if (entries.isEmpty) return;
216 |
217 | final frames = [];
218 | for (final entry in entries.entries) {
219 | final frame = Frame(
220 | id: collection.autoIncrement(),
221 | typeId: Hive._typeRegistry.findTypeId(entry.value),
222 | key: entry.key,
223 | value: entry.value,
224 | );
225 | frames.add(frame);
226 | }
227 | collection.putAll(frames);
228 | });
229 | }
230 |
231 | @override
232 | void putRange(int start, int end, Iterable values) {
233 | write(() {
234 | if (start == 0 && end == 0) {
235 | return;
236 | }
237 |
238 | final idsInRange = collection
239 | .where()
240 | .idProperty()
241 | .findAll(offset: start, limit: end - start);
242 |
243 | if (idsInRange.length != end - start) {
244 | RangeError.checkValidRange(start, end, length);
245 | throw ArgumentError.value(
246 | values,
247 | 'values',
248 | 'must have the same length as the range',
249 | );
250 | }
251 |
252 | final frames = [];
253 | for (final value in values) {
254 | final frame = Frame(
255 | id: idsInRange[frames.length],
256 | typeId: Hive._typeRegistry.findTypeId(value),
257 | value: value,
258 | );
259 | frames.add(frame);
260 | }
261 | collection.putAll(frames);
262 | });
263 | }
264 |
265 | @override
266 | void add(E value, {String? key}) {
267 | write(() {
268 | final frame = Frame(
269 | id: collection.autoIncrement(),
270 | typeId: Hive._typeRegistry.findTypeId(value),
271 | key: key,
272 | value: value,
273 | );
274 | collection.put(frame);
275 | });
276 | }
277 |
278 | @override
279 | void addAll(Iterable values) {
280 | write(() {
281 | final frames = [];
282 | for (final value in values) {
283 | final frame = Frame(
284 | id: collection.autoIncrement(),
285 | typeId: Hive._typeRegistry.findTypeId(value),
286 | value: value,
287 | );
288 | frames.add(frame);
289 | }
290 | collection.putAll(frames);
291 | });
292 | }
293 |
294 | @override
295 | bool delete(String key) {
296 | return write(() {
297 | return collection.where().keyEqualTo(key).deleteFirst();
298 | });
299 | }
300 |
301 | @override
302 | void deleteAt(int index) {
303 | return write(() {
304 | final deleted = collection.where().deleteFirst(offset: index);
305 | if (!deleted) {
306 | throw IndexError.withLength(index, length);
307 | }
308 | });
309 | }
310 |
311 | @override
312 | int deleteAll(Iterable keys) {
313 | return write(() {
314 | if (keys.isEmpty) return 0;
315 | return collection
316 | .where()
317 | // ignore: inference_failure_on_function_invocation
318 | .anyOf(keys, (q, key) => q.keyEqualTo(key))
319 | .deleteAll();
320 | });
321 | }
322 |
323 | @override
324 | void deleteRange(int start, int end) {
325 | return write(() {
326 | if (start == 0 && end == 0) {
327 | return;
328 | }
329 |
330 | final deleted =
331 | collection.where().deleteAll(offset: start, limit: end - start);
332 |
333 | if (deleted != end - start) {
334 | RangeError.checkValidRange(start, end, length);
335 | }
336 | });
337 | }
338 |
339 | @override
340 | void clear({bool notify = true}) {
341 | isar.write((isar) {
342 | collection.clear();
343 | });
344 | }
345 |
346 | @override
347 | void close() {
348 | Hive._openBoxes.remove(name);
349 | isar.close();
350 | }
351 |
352 | @override
353 | void deleteFromDisk() {
354 | Hive._openBoxes.remove(name);
355 | isar.close(deleteFromDisk: true);
356 | }
357 |
358 | @override
359 | Stream watchKey(String key) {
360 | return isar.frames.where().keyEqualTo(key).watch().map((frames) {
361 | final frame = frames.firstOrNull;
362 | if (frame == null) {
363 | return null;
364 | } else {
365 | return _frameFromJson(frame);
366 | }
367 | });
368 | }
369 |
370 | @override
371 | Stream watch() {
372 | return isar.frames.watchLazy();
373 | }
374 | }
375 |
--------------------------------------------------------------------------------
/lib/src/impl/frame.dart:
--------------------------------------------------------------------------------
1 | import 'package:isar/isar.dart';
2 |
3 | part 'frame.g.dart';
4 |
5 | /// @nodoc
6 | @collection
7 | class Frame {
8 | /// @nodoc
9 | const Frame({
10 | required this.id,
11 | required this.typeId,
12 | this.key,
13 | required this.value,
14 | });
15 |
16 | /// @nodoc
17 | final int id;
18 |
19 | /// @nodoc
20 | final int? typeId;
21 |
22 | /// @nodoc
23 | @Index(unique: true, hash: true)
24 | final String? key;
25 |
26 | /// @nodoc
27 | final dynamic value;
28 | }
29 |
--------------------------------------------------------------------------------
/lib/src/impl/frame.g.dart:
--------------------------------------------------------------------------------
1 | // GENERATED CODE - DO NOT MODIFY BY HAND
2 |
3 | part of 'frame.dart';
4 |
5 | // **************************************************************************
6 | // _IsarCollectionGenerator
7 | // **************************************************************************
8 |
9 | // coverage:ignore-file
10 | // ignore_for_file: duplicate_ignore, invalid_use_of_protected_member, lines_longer_than_80_chars, constant_identifier_names, avoid_js_rounded_ints, no_leading_underscores_for_local_identifiers, require_trailing_commas, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_in_if_null_operators, library_private_types_in_public_api, prefer_const_constructors
11 | // ignore_for_file: type=lint
12 |
13 | extension GetFrameCollection on Isar {
14 | IsarCollection get frames => this.collection();
15 | }
16 |
17 | const FrameSchema = IsarGeneratedSchema(
18 | schema: IsarSchema(
19 | name: 'Frame',
20 | idName: 'id',
21 | embedded: false,
22 | properties: [
23 | IsarPropertySchema(
24 | name: 'typeId',
25 | type: IsarType.long,
26 | ),
27 | IsarPropertySchema(
28 | name: 'key',
29 | type: IsarType.string,
30 | ),
31 | IsarPropertySchema(
32 | name: 'value',
33 | type: IsarType.json,
34 | ),
35 | ],
36 | indexes: [
37 | IsarIndexSchema(
38 | name: 'key',
39 | properties: [
40 | "key",
41 | ],
42 | unique: true,
43 | hash: true,
44 | ),
45 | ],
46 | ),
47 | converter: IsarObjectConverter(
48 | serialize: serializeFrame,
49 | deserialize: deserializeFrame,
50 | deserializeProperty: deserializeFrameProp,
51 | ),
52 | embeddedSchemas: [],
53 | );
54 |
55 | @isarProtected
56 | int serializeFrame(IsarWriter writer, Frame object) {
57 | IsarCore.writeLong(writer, 1, object.typeId ?? -9223372036854775808);
58 | {
59 | final value = object.key;
60 | if (value == null) {
61 | IsarCore.writeNull(writer, 2);
62 | } else {
63 | IsarCore.writeString(writer, 2, value);
64 | }
65 | }
66 | IsarCore.writeString(writer, 3, isarJsonEncode(object.value));
67 | return object.id;
68 | }
69 |
70 | @isarProtected
71 | Frame deserializeFrame(IsarReader reader) {
72 | final int _id;
73 | _id = IsarCore.readId(reader);
74 | final int? _typeId;
75 | {
76 | final value = IsarCore.readLong(reader, 1);
77 | if (value == -9223372036854775808) {
78 | _typeId = null;
79 | } else {
80 | _typeId = value;
81 | }
82 | }
83 | final String? _key;
84 | _key = IsarCore.readString(reader, 2);
85 | final dynamic _value;
86 | _value = isarJsonDecode(IsarCore.readString(reader, 3) ?? 'null') ?? null;
87 | final object = Frame(
88 | id: _id,
89 | typeId: _typeId,
90 | key: _key,
91 | value: _value,
92 | );
93 | return object;
94 | }
95 |
96 | @isarProtected
97 | dynamic deserializeFrameProp(IsarReader reader, int property) {
98 | switch (property) {
99 | case 0:
100 | return IsarCore.readId(reader);
101 | case 1:
102 | {
103 | final value = IsarCore.readLong(reader, 1);
104 | if (value == -9223372036854775808) {
105 | return null;
106 | } else {
107 | return value;
108 | }
109 | }
110 | case 2:
111 | return IsarCore.readString(reader, 2);
112 | case 3:
113 | return isarJsonDecode(IsarCore.readString(reader, 3) ?? 'null') ?? null;
114 | default:
115 | throw ArgumentError('Unknown property: $property');
116 | }
117 | }
118 |
119 | sealed class _FrameUpdate {
120 | bool call({
121 | required int id,
122 | int? typeId,
123 | String? key,
124 | });
125 | }
126 |
127 | class _FrameUpdateImpl implements _FrameUpdate {
128 | const _FrameUpdateImpl(this.collection);
129 |
130 | final IsarCollection collection;
131 |
132 | @override
133 | bool call({
134 | required int id,
135 | Object? typeId = ignore,
136 | Object? key = ignore,
137 | }) {
138 | return collection.updateProperties([
139 | id
140 | ], {
141 | if (typeId != ignore) 1: typeId as int?,
142 | if (key != ignore) 2: key as String?,
143 | }) >
144 | 0;
145 | }
146 | }
147 |
148 | sealed class _FrameUpdateAll {
149 | int call({
150 | required List id,
151 | int? typeId,
152 | String? key,
153 | });
154 | }
155 |
156 | class _FrameUpdateAllImpl implements _FrameUpdateAll {
157 | const _FrameUpdateAllImpl(this.collection);
158 |
159 | final IsarCollection collection;
160 |
161 | @override
162 | int call({
163 | required List id,
164 | Object? typeId = ignore,
165 | Object? key = ignore,
166 | }) {
167 | return collection.updateProperties(id, {
168 | if (typeId != ignore) 1: typeId as int?,
169 | if (key != ignore) 2: key as String?,
170 | });
171 | }
172 | }
173 |
174 | extension FrameUpdate on IsarCollection {
175 | _FrameUpdate get update => _FrameUpdateImpl(this);
176 |
177 | _FrameUpdateAll get updateAll => _FrameUpdateAllImpl(this);
178 | }
179 |
180 | sealed class _FrameQueryUpdate {
181 | int call({
182 | int? typeId,
183 | String? key,
184 | });
185 | }
186 |
187 | class _FrameQueryUpdateImpl implements _FrameQueryUpdate {
188 | const _FrameQueryUpdateImpl(this.query, {this.limit});
189 |
190 | final IsarQuery query;
191 | final int? limit;
192 |
193 | @override
194 | int call({
195 | Object? typeId = ignore,
196 | Object? key = ignore,
197 | }) {
198 | return query.updateProperties(limit: limit, {
199 | if (typeId != ignore) 1: typeId as int?,
200 | if (key != ignore) 2: key as String?,
201 | });
202 | }
203 | }
204 |
205 | extension FrameQueryUpdate on IsarQuery {
206 | _FrameQueryUpdate get updateFirst => _FrameQueryUpdateImpl(this, limit: 1);
207 |
208 | _FrameQueryUpdate get updateAll => _FrameQueryUpdateImpl(this);
209 | }
210 |
211 | class _FrameQueryBuilderUpdateImpl implements _FrameQueryUpdate {
212 | const _FrameQueryBuilderUpdateImpl(this.query, {this.limit});
213 |
214 | final QueryBuilder query;
215 | final int? limit;
216 |
217 | @override
218 | int call({
219 | Object? typeId = ignore,
220 | Object? key = ignore,
221 | }) {
222 | final q = query.build();
223 | try {
224 | return q.updateProperties(limit: limit, {
225 | if (typeId != ignore) 1: typeId as int?,
226 | if (key != ignore) 2: key as String?,
227 | });
228 | } finally {
229 | q.close();
230 | }
231 | }
232 | }
233 |
234 | extension FrameQueryBuilderUpdate on QueryBuilder {
235 | _FrameQueryUpdate get updateFirst =>
236 | _FrameQueryBuilderUpdateImpl(this, limit: 1);
237 |
238 | _FrameQueryUpdate get updateAll => _FrameQueryBuilderUpdateImpl(this);
239 | }
240 |
241 | extension FrameQueryFilter on QueryBuilder {
242 | QueryBuilder idEqualTo(
243 | int value,
244 | ) {
245 | return QueryBuilder.apply(this, (query) {
246 | return query.addFilterCondition(
247 | EqualCondition(
248 | property: 0,
249 | value: value,
250 | ),
251 | );
252 | });
253 | }
254 |
255 | QueryBuilder idGreaterThan(
256 | int value,
257 | ) {
258 | return QueryBuilder.apply(this, (query) {
259 | return query.addFilterCondition(
260 | GreaterCondition(
261 | property: 0,
262 | value: value,
263 | ),
264 | );
265 | });
266 | }
267 |
268 | QueryBuilder idGreaterThanOrEqualTo(
269 | int value,
270 | ) {
271 | return QueryBuilder.apply(this, (query) {
272 | return query.addFilterCondition(
273 | GreaterOrEqualCondition(
274 | property: 0,
275 | value: value,
276 | ),
277 | );
278 | });
279 | }
280 |
281 | QueryBuilder idLessThan(
282 | int value,
283 | ) {
284 | return QueryBuilder.apply(this, (query) {
285 | return query.addFilterCondition(
286 | LessCondition(
287 | property: 0,
288 | value: value,
289 | ),
290 | );
291 | });
292 | }
293 |
294 | QueryBuilder idLessThanOrEqualTo(
295 | int value,
296 | ) {
297 | return QueryBuilder.apply(this, (query) {
298 | return query.addFilterCondition(
299 | LessOrEqualCondition(
300 | property: 0,
301 | value: value,
302 | ),
303 | );
304 | });
305 | }
306 |
307 | QueryBuilder idBetween(
308 | int lower,
309 | int upper,
310 | ) {
311 | return QueryBuilder.apply(this, (query) {
312 | return query.addFilterCondition(
313 | BetweenCondition(
314 | property: 0,
315 | lower: lower,
316 | upper: upper,
317 | ),
318 | );
319 | });
320 | }
321 |
322 | QueryBuilder typeIdIsNull() {
323 | return QueryBuilder.apply(this, (query) {
324 | return query.addFilterCondition(const IsNullCondition(property: 1));
325 | });
326 | }
327 |
328 | QueryBuilder typeIdIsNotNull() {
329 | return QueryBuilder.apply(not(), (query) {
330 | return query.addFilterCondition(const IsNullCondition(property: 1));
331 | });
332 | }
333 |
334 | QueryBuilder typeIdEqualTo(
335 | int? value,
336 | ) {
337 | return QueryBuilder.apply(this, (query) {
338 | return query.addFilterCondition(
339 | EqualCondition(
340 | property: 1,
341 | value: value,
342 | ),
343 | );
344 | });
345 | }
346 |
347 | QueryBuilder typeIdGreaterThan(
348 | int? value,
349 | ) {
350 | return QueryBuilder.apply(this, (query) {
351 | return query.addFilterCondition(
352 | GreaterCondition(
353 | property: 1,
354 | value: value,
355 | ),
356 | );
357 | });
358 | }
359 |
360 | QueryBuilder typeIdGreaterThanOrEqualTo(
361 | int? value,
362 | ) {
363 | return QueryBuilder.apply(this, (query) {
364 | return query.addFilterCondition(
365 | GreaterOrEqualCondition(
366 | property: 1,
367 | value: value,
368 | ),
369 | );
370 | });
371 | }
372 |
373 | QueryBuilder typeIdLessThan(
374 | int? value,
375 | ) {
376 | return QueryBuilder.apply(this, (query) {
377 | return query.addFilterCondition(
378 | LessCondition(
379 | property: 1,
380 | value: value,
381 | ),
382 | );
383 | });
384 | }
385 |
386 | QueryBuilder typeIdLessThanOrEqualTo(
387 | int? value,
388 | ) {
389 | return QueryBuilder.apply(this, (query) {
390 | return query.addFilterCondition(
391 | LessOrEqualCondition(
392 | property: 1,
393 | value: value,
394 | ),
395 | );
396 | });
397 | }
398 |
399 | QueryBuilder typeIdBetween(
400 | int? lower,
401 | int? upper,
402 | ) {
403 | return QueryBuilder.apply(this, (query) {
404 | return query.addFilterCondition(
405 | BetweenCondition(
406 | property: 1,
407 | lower: lower,
408 | upper: upper,
409 | ),
410 | );
411 | });
412 | }
413 |
414 | QueryBuilder keyIsNull() {
415 | return QueryBuilder.apply(this, (query) {
416 | return query.addFilterCondition(const IsNullCondition(property: 2));
417 | });
418 | }
419 |
420 | QueryBuilder keyIsNotNull() {
421 | return QueryBuilder.apply(not(), (query) {
422 | return query.addFilterCondition(const IsNullCondition(property: 2));
423 | });
424 | }
425 |
426 | QueryBuilder keyEqualTo(
427 | String? value, {
428 | bool caseSensitive = true,
429 | }) {
430 | return QueryBuilder.apply(this, (query) {
431 | return query.addFilterCondition(
432 | EqualCondition(
433 | property: 2,
434 | value: value,
435 | caseSensitive: caseSensitive,
436 | ),
437 | );
438 | });
439 | }
440 |
441 | QueryBuilder keyGreaterThan(
442 | String? value, {
443 | bool caseSensitive = true,
444 | }) {
445 | return QueryBuilder.apply(this, (query) {
446 | return query.addFilterCondition(
447 | GreaterCondition(
448 | property: 2,
449 | value: value,
450 | caseSensitive: caseSensitive,
451 | ),
452 | );
453 | });
454 | }
455 |
456 | QueryBuilder keyGreaterThanOrEqualTo(
457 | String? value, {
458 | bool caseSensitive = true,
459 | }) {
460 | return QueryBuilder.apply(this, (query) {
461 | return query.addFilterCondition(
462 | GreaterOrEqualCondition(
463 | property: 2,
464 | value: value,
465 | caseSensitive: caseSensitive,
466 | ),
467 | );
468 | });
469 | }
470 |
471 | QueryBuilder keyLessThan(
472 | String? value, {
473 | bool caseSensitive = true,
474 | }) {
475 | return QueryBuilder.apply(this, (query) {
476 | return query.addFilterCondition(
477 | LessCondition(
478 | property: 2,
479 | value: value,
480 | caseSensitive: caseSensitive,
481 | ),
482 | );
483 | });
484 | }
485 |
486 | QueryBuilder keyLessThanOrEqualTo(
487 | String? value, {
488 | bool caseSensitive = true,
489 | }) {
490 | return QueryBuilder.apply(this, (query) {
491 | return query.addFilterCondition(
492 | LessOrEqualCondition(
493 | property: 2,
494 | value: value,
495 | caseSensitive: caseSensitive,
496 | ),
497 | );
498 | });
499 | }
500 |
501 | QueryBuilder keyBetween(
502 | String? lower,
503 | String? upper, {
504 | bool caseSensitive = true,
505 | }) {
506 | return QueryBuilder.apply(this, (query) {
507 | return query.addFilterCondition(
508 | BetweenCondition(
509 | property: 2,
510 | lower: lower,
511 | upper: upper,
512 | caseSensitive: caseSensitive,
513 | ),
514 | );
515 | });
516 | }
517 |
518 | QueryBuilder keyStartsWith(
519 | String value, {
520 | bool caseSensitive = true,
521 | }) {
522 | return QueryBuilder.apply(this, (query) {
523 | return query.addFilterCondition(
524 | StartsWithCondition(
525 | property: 2,
526 | value: value,
527 | caseSensitive: caseSensitive,
528 | ),
529 | );
530 | });
531 | }
532 |
533 | QueryBuilder keyEndsWith(
534 | String value, {
535 | bool caseSensitive = true,
536 | }) {
537 | return QueryBuilder.apply(this, (query) {
538 | return query.addFilterCondition(
539 | EndsWithCondition(
540 | property: 2,
541 | value: value,
542 | caseSensitive: caseSensitive,
543 | ),
544 | );
545 | });
546 | }
547 |
548 | QueryBuilder keyContains(String value,
549 | {bool caseSensitive = true}) {
550 | return QueryBuilder.apply(this, (query) {
551 | return query.addFilterCondition(
552 | ContainsCondition(
553 | property: 2,
554 | value: value,
555 | caseSensitive: caseSensitive,
556 | ),
557 | );
558 | });
559 | }
560 |
561 | QueryBuilder keyMatches(String pattern,
562 | {bool caseSensitive = true}) {
563 | return QueryBuilder.apply(this, (query) {
564 | return query.addFilterCondition(
565 | MatchesCondition(
566 | property: 2,
567 | wildcard: pattern,
568 | caseSensitive: caseSensitive,
569 | ),
570 | );
571 | });
572 | }
573 |
574 | QueryBuilder keyIsEmpty() {
575 | return QueryBuilder.apply(this, (query) {
576 | return query.addFilterCondition(
577 | const EqualCondition(
578 | property: 2,
579 | value: '',
580 | ),
581 | );
582 | });
583 | }
584 |
585 | QueryBuilder keyIsNotEmpty() {
586 | return QueryBuilder.apply(this, (query) {
587 | return query.addFilterCondition(
588 | const GreaterCondition(
589 | property: 2,
590 | value: '',
591 | ),
592 | );
593 | });
594 | }
595 | }
596 |
597 | extension FrameQueryObject on QueryBuilder {}
598 |
599 | extension FrameQuerySortBy on QueryBuilder {
600 | QueryBuilder sortById() {
601 | return QueryBuilder.apply(this, (query) {
602 | return query.addSortBy(0);
603 | });
604 | }
605 |
606 | QueryBuilder sortByIdDesc() {
607 | return QueryBuilder.apply(this, (query) {
608 | return query.addSortBy(0, sort: Sort.desc);
609 | });
610 | }
611 |
612 | QueryBuilder sortByTypeId() {
613 | return QueryBuilder.apply(this, (query) {
614 | return query.addSortBy(1);
615 | });
616 | }
617 |
618 | QueryBuilder sortByTypeIdDesc() {
619 | return QueryBuilder.apply(this, (query) {
620 | return query.addSortBy(1, sort: Sort.desc);
621 | });
622 | }
623 |
624 | QueryBuilder sortByKey(
625 | {bool caseSensitive = true}) {
626 | return QueryBuilder.apply(this, (query) {
627 | return query.addSortBy(
628 | 2,
629 | caseSensitive: caseSensitive,
630 | );
631 | });
632 | }
633 |
634 | QueryBuilder sortByKeyDesc(
635 | {bool caseSensitive = true}) {
636 | return QueryBuilder.apply(this, (query) {
637 | return query.addSortBy(
638 | 2,
639 | sort: Sort.desc,
640 | caseSensitive: caseSensitive,
641 | );
642 | });
643 | }
644 |
645 | QueryBuilder sortByValue() {
646 | return QueryBuilder.apply(this, (query) {
647 | return query.addSortBy(3);
648 | });
649 | }
650 |
651 | QueryBuilder sortByValueDesc() {
652 | return QueryBuilder.apply(this, (query) {
653 | return query.addSortBy(3, sort: Sort.desc);
654 | });
655 | }
656 | }
657 |
658 | extension FrameQuerySortThenBy on QueryBuilder {
659 | QueryBuilder thenById() {
660 | return QueryBuilder.apply(this, (query) {
661 | return query.addSortBy(0);
662 | });
663 | }
664 |
665 | QueryBuilder thenByIdDesc() {
666 | return QueryBuilder.apply(this, (query) {
667 | return query.addSortBy(0, sort: Sort.desc);
668 | });
669 | }
670 |
671 | QueryBuilder thenByTypeId() {
672 | return QueryBuilder.apply(this, (query) {
673 | return query.addSortBy(1);
674 | });
675 | }
676 |
677 | QueryBuilder thenByTypeIdDesc() {
678 | return QueryBuilder.apply(this, (query) {
679 | return query.addSortBy(1, sort: Sort.desc);
680 | });
681 | }
682 |
683 | QueryBuilder thenByKey(
684 | {bool caseSensitive = true}) {
685 | return QueryBuilder.apply(this, (query) {
686 | return query.addSortBy(2, caseSensitive: caseSensitive);
687 | });
688 | }
689 |
690 | QueryBuilder thenByKeyDesc(
691 | {bool caseSensitive = true}) {
692 | return QueryBuilder.apply(this, (query) {
693 | return query.addSortBy(2, sort: Sort.desc, caseSensitive: caseSensitive);
694 | });
695 | }
696 |
697 | QueryBuilder thenByValue() {
698 | return QueryBuilder.apply(this, (query) {
699 | return query.addSortBy(3);
700 | });
701 | }
702 |
703 | QueryBuilder thenByValueDesc() {
704 | return QueryBuilder.apply(this, (query) {
705 | return query.addSortBy(3, sort: Sort.desc);
706 | });
707 | }
708 | }
709 |
710 | extension FrameQueryWhereDistinct on QueryBuilder {
711 | QueryBuilder distinctByTypeId() {
712 | return QueryBuilder.apply(this, (query) {
713 | return query.addDistinctBy(1);
714 | });
715 | }
716 |
717 | QueryBuilder distinctByKey(
718 | {bool caseSensitive = true}) {
719 | return QueryBuilder.apply(this, (query) {
720 | return query.addDistinctBy(2, caseSensitive: caseSensitive);
721 | });
722 | }
723 |
724 | QueryBuilder distinctByValue() {
725 | return QueryBuilder.apply(this, (query) {
726 | return query.addDistinctBy(3);
727 | });
728 | }
729 | }
730 |
731 | extension FrameQueryProperty1 on QueryBuilder {
732 | QueryBuilder idProperty() {
733 | return QueryBuilder.apply(this, (query) {
734 | return query.addProperty(0);
735 | });
736 | }
737 |
738 | QueryBuilder typeIdProperty() {
739 | return QueryBuilder.apply(this, (query) {
740 | return query.addProperty(1);
741 | });
742 | }
743 |
744 | QueryBuilder keyProperty() {
745 | return QueryBuilder.apply(this, (query) {
746 | return query.addProperty(2);
747 | });
748 | }
749 |
750 | QueryBuilder valueProperty() {
751 | return QueryBuilder.apply(this, (query) {
752 | return query.addProperty(3);
753 | });
754 | }
755 | }
756 |
757 | extension FrameQueryProperty2 on QueryBuilder {
758 | QueryBuilder idProperty() {
759 | return QueryBuilder.apply(this, (query) {
760 | return query.addProperty(0);
761 | });
762 | }
763 |
764 | QueryBuilder typeIdProperty() {
765 | return QueryBuilder.apply(this, (query) {
766 | return query.addProperty(1);
767 | });
768 | }
769 |
770 | QueryBuilder keyProperty() {
771 | return QueryBuilder.apply(this, (query) {
772 | return query.addProperty(2);
773 | });
774 | }
775 |
776 | QueryBuilder valueProperty() {
777 | return QueryBuilder.apply(this, (query) {
778 | return query.addProperty(3);
779 | });
780 | }
781 | }
782 |
783 | extension FrameQueryProperty3
784 | on QueryBuilder {
785 | QueryBuilder idProperty() {
786 | return QueryBuilder.apply(this, (query) {
787 | return query.addProperty(0);
788 | });
789 | }
790 |
791 | QueryBuilder typeIdProperty() {
792 | return QueryBuilder.apply(this, (query) {
793 | return query.addProperty(1);
794 | });
795 | }
796 |
797 | QueryBuilder keyProperty() {
798 | return QueryBuilder.apply(this, (query) {
799 | return query.addProperty(2);
800 | });
801 | }
802 |
803 | QueryBuilder valueProperty() {
804 | return QueryBuilder.apply(this, (query) {
805 | return query.addProperty(3);
806 | });
807 | }
808 | }
809 |
--------------------------------------------------------------------------------
/lib/src/impl/isolate_stub.dart:
--------------------------------------------------------------------------------
1 | import 'dart:async';
2 |
3 | /// @nodoc
4 | class Isolate {
5 | /// @nodoc
6 | static Future run(
7 | FutureOr Function() computation, {
8 | String? debugName,
9 | }) {
10 | throw UnimplementedError(
11 | 'Isolate.run is not implemented on this platform.',
12 | );
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/lib/src/impl/type_registry.dart:
--------------------------------------------------------------------------------
1 | part of hive;
2 |
3 | const _builtinTypes = {
4 | bool: _TypeHandler.builtin(),
5 | num: _TypeHandler.builtin(),
6 | String: _TypeHandler.builtin(),
7 | List: _TypeHandler>.builtin(),
8 | Map: _TypeHandler