### Creating Flutter Project (Bash) Source: https://github.com/isar/hive/blob/main/example/README.md These Bash commands are used to create a new Flutter project named 'bee_favorites' and then navigate into the newly created project directory. ```bash flutter create bee_favorites cd bee_favorites ``` -------------------------------- ### Initializing Flutter and Hive (Dart) Source: https://github.com/isar/hive/blob/main/example/README.md This Dart code initializes Flutter bindings, gets the application's documents directory using path_provider, sets this directory as Hive's default storage location, and then runs the main Flutter application widget. ```dart import 'package:flutter/material.dart'; import 'package:hive/hive.dart'; import 'package:path_provider/path_provider.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); final directory = await getApplicationDocumentsDirectory(); Hive.defaultDirectory = directory.path; runApp(BeeApp()); } ``` -------------------------------- ### Adding Dependencies to pubspec.yaml (YAML) Source: https://github.com/isar/hive/blob/main/example/README.md This YAML snippet shows the required dependencies to add to the `pubspec.yaml` file for using Flutter, Hive, Isar (via libs), and path_provider in the project. ```yaml dependencies: flutter: sdk: flutter hive: ^4.0.0 isar_flutter_libs: ^4.0.0-dev.13 path_provider: ^2.0.0 ``` -------------------------------- ### Building Flutter UI with Hive Interaction (Dart) Source: https://github.com/isar/hive/blob/main/example/README.md This comprehensive Dart code defines the main Flutter application structure, including a `StatelessWidget` for the app itself and a `StatefulWidget` (`FavoriteFlowers`) that manages the UI state. It demonstrates opening a Hive Box named 'favorites', displaying a list of items, adding selected items to the Hive box on button press, showing a SnackBar confirmation, and displaying the current favorites from the box in an AlertDialog (`FavoritesDialog`). ```dart class BeeApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Bee Favorites', theme: ThemeData(primarySwatch: Colors.yellow), home: FavoriteFlowers(), ); } } class FavoriteFlowers extends StatefulWidget { @override _FavoriteFlowersState createState() => _FavoriteFlowersState(); } class _FavoriteFlowersState extends State { final Box favoriteBox = Hive.box('favorites'); final List flowers = ['Rose', 'Tulip', 'Daisy', 'Lily', 'Sunflower']; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Bee Favorites 🐝')), body: ListView.builder( itemCount: flowers.length, itemBuilder: (context, index) { final flower = flowers[index]; return ListTile( title: Text(flower), trailing: IconButton( icon: Icon(Icons.star), onPressed: () { favoriteBox.add(flower); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('$flower added to favorites! 🌼')), ); }, ), ); }, ), floatingActionButton: FloatingActionButton( child: Icon(Icons.view_list), onPressed: () { showDialog( context: context, builder: (context) => FavoritesDialog(favorites: favoriteBox.values.toList()), ); }, ), ); } } class FavoritesDialog extends StatelessWidget { final List favorites; FavoritesDialog({required this.favorites}); @override Widget build(BuildContext context) { return AlertDialog( title: Text('Bee Favorites 🌼'), content: Container( width: 300, height: 200, child: ListView.builder( itemCount: favorites.length, itemBuilder: (context, index) { return ListTile(title: Text(favorites[index])); }, ), ), actions: [ TextButton( child: Text('Close'), onPressed: () => Navigator.of(context).pop(), ), ], ); } } ``` -------------------------------- ### Reading Data from Hive Box using Get with Default in Dart Source: https://github.com/isar/hive/blob/main/README.md Shows how to retrieve data from a Hive box using `box.get(key)`. If the specified key does not exist, the method returns `null`. The example also demonstrates using the optional `defaultValue` parameter to provide a fallback value if the key is not found. ```Dart final box = Hive.box(name: 'beeees'); final fav = box.get('favoriteFlower'); final moves = box.get('danceMoves', defaultValue: 'waggle'); ``` -------------------------------- ### Reading Data from Hive Box using Map Syntax in Dart Source: https://github.com/isar/hive/blob/main/README.md Demonstrates retrieving values from a Hive box using the standard Dart map lookup syntax `box[key]`. This method returns `null` if the key is not found. The example uses the `??` operator to provide a default value if the result is `null`. ```Dart final fav = box['favoriteFlower']; final moves = box['danceMoves'] ?? 'waggle'; ``` -------------------------------- ### Performing Basic Hive Operations (Put/Get) in Dart Source: https://github.com/isar/hive/blob/main/README.md Demonstrates how to open the default Hive box, store a string value associated with a key using `box.put()`, retrieve the value using `box.get()`, and print the retrieved data. Requires importing `package:hive/hive.dart`. ```Dart import 'package:hive/hive.dart'; final box = Hive.box(); box.put('name', 'David'); final name = box.get('name'); print('Name: $name'); ``` -------------------------------- ### Adding Hive Dependencies in Pubspec YAML Source: https://github.com/isar/hive/blob/main/README.md Describes how to add the required dependencies, `hive`, `isar_flutter_libs`, and `path_provider`, to your project's `pubspec.yaml` file. `path_provider` is included to help identify suitable directories across different platforms for Hive storage. ```YAML dependencies: hive: ^4.0.0 isar_flutter_libs: ^4.0.0-dev.13 path_provider: ^2.1.0 ``` -------------------------------- ### Storing and Retrieving Custom Objects - Dart Source: https://github.com/isar/hive/blob/main/README.md Demonstrates how to instantiate the custom `Bee` class, store an instance in a Hive box using a specific key, and then retrieve the object using the same key. The output shows the object successfully retrieved and implicitly converted back to a `Bee` instance. ```Dart final box = Hive.box(); final bumble = Bee(name: 'Bumble', role: 'Worker'); box.put('BumbleID', bumble); print(box.get('BumbleID')); // Bumble - Worker ``` -------------------------------- ### Inserting Multiple Entries using PutAll in Hive Dart Source: https://github.com/isar/hive/blob/main/README.md Demonstrates how to efficiently insert multiple key-value pairs into a Hive box in a single operation using the `box.putAll()` method. This method accepts a `Map` where keys are strings and values are the data to be stored. ```Dart box.putAll({'favoriteFlower': 'Lavender', 'wingSpeed': 210}); ``` -------------------------------- ### Adding Values to Hive Box using Add (List-like) in Dart Source: https://github.com/isar/hive/blob/main/README.md Demonstrates using a Hive box like a list by adding values sequentially using the `box.add()` method. Hive automatically assigns incremental integer keys to these values. Values can then be retrieved by their integer index using `box.getAt(index)`. ```Dart final box = Hive.box(); box.add('Rose'); box.add('Tulip'); print(box.getAt(0)); // Rose print(box.getAt(1)); // Tulip ``` -------------------------------- ### Designating Hive Default Directory in Dart Source: https://github.com/isar/hive/blob/main/README.md Explains how to initialize the Flutter binding, find a valid application directory using `path_provider.getApplicationDocumentsDirectory()`, and set it as the default storage location for Hive boxes using `Hive.defaultDirectory` within your Dart application's `main` function. ```Dart void main() async { WidgetsFlutterBinding.ensureInitialized(); final dir = await getApplicationDocumentsDirectory(); Hive.defaultDirectory = dir.path; // ... } ``` -------------------------------- ### Performing Write and Read Transactions - Dart Source: https://github.com/isar/hive/blob/main/README.md Illustrates the use of Hive's `write()` and `read()` methods for grouping database operations within transactions. `write()` ensures atomicity for changes within the block, while `read()` provides a consistent view for reads. ```Dart final box = Hive.box(); box.write(() { box.store('nectar1', 'GoldenNectar'); box.store('nectar2', 'WildflowerBrew'); box.store('nectar3', 'CloverDew'); }); box.read(() { box.get('nectar1'); // GoldenNectar }); ``` -------------------------------- ### Inserting Data into Hive Box using Map Syntax in Dart Source: https://github.com/isar/hive/blob/main/README.md Presents an alternative syntax for inserting or updating key-value pairs in a Hive box using the standard Dart map assignment syntax `box[key] = value;`. This provides a familiar way to interact with the box. ```Dart box['danceMoves'] = 'Round Dance'; box['wingSpeed'] = 220; ``` -------------------------------- ### Opening a Named Hive Box in Dart Source: https://github.com/isar/hive/blob/main/README.md Shows the syntax for opening a Hive box with a specific name using `Hive.box(name: 'myBox')`. If a box with the given name doesn't exist, it will be created; otherwise, the existing box is returned. This allows for organizing data into separate containers. ```Dart final box = Hive.box(name: 'myBox'); ``` -------------------------------- ### Inserting Data into Hive Box using Put in Dart Source: https://github.com/isar/hive/blob/main/README.md Demonstrates storing simple key-value pairs (String key to String or int value) in a Hive box using the `box.put()` method. If the key already exists, its corresponding value is updated. ```Dart final box = Hive.box(); box.put('danceMoves', 'Waggle Dance'); box.put('wingSpeed', 200); ``` -------------------------------- ### Registering Custom Object Adapter - Dart Source: https://github.com/isar/hive/blob/main/README.md Registers the custom `Bee` class with Hive, providing the `fromJson` factory method as the adapter function. This allows Hive to correctly deserialize data for the `Bee` type when retrieving it from a box. ```Dart Hive.registerAdapter('Bee', Bee.fromJson); ``` -------------------------------- ### Demonstrating Transaction Atomicity (Rollback) - Dart Source: https://github.com/isar/hive/blob/main/README.md Shows how Hive transactions are atomic. An initial value is set, then a `write()` transaction attempts to update it and deliberately throws an exception. Because of atomicity, the exception causes the transaction to roll back, and the original value is preserved in the box. ```Dart final box = Hive.box(); box.put('honeyLevel', 5); box.write(() { box.put('honeyLevel', 6); throw Exception('Oh no!!!'); }); print(box.get('honeyLevel')); // 5 ``` -------------------------------- ### Accessing Hive Box by Name Dart Source: https://github.com/isar/hive/blob/main/CHANGELOG.md This snippet illustrates how to access a previously registered or opened Hive box instance using its string name as a key, similar to accessing an item in a map. The accompanying changelog entry notes that a bug fix in version 0.3.0+1 resolved an issue where this syntax failed when the box name contained uppercase characters. ```Dart Hive['yourBox'] ``` -------------------------------- ### Running Hive Operations in a Separate Isolate - Dart Source: https://github.com/isar/hive/blob/main/README.md Demonstrates using `Hive.compute()` to execute a function containing Hive operations (accessing and updating data) on a separate isolate. This prevents blocking the main UI thread. It shows that the same box instance can be accessed from different isolates. ```Dart // Opening the bee's box final box = Hive.box(); // Storing some sweet nectar box.put('nectarType', 'wildflower'); await Hive.compute(() { // Accessing the same box from another worker bee final box = Hive.box(); print(box.get('nectarType')); // wildflower // Updating the nectar's quality box.put('nectarType', 'lavender'); }); // Tasting the updated honey flavor print(honeycomb.get('nectarType')); // lavender ``` -------------------------------- ### Accessing Values by Index After Mixing Add and Put in Hive Dart Source: https://github.com/isar/hive/blob/main/README.md Illustrates that a Hive box can be used with both key-based (`put`) and index-based (`add`) operations simultaneously. Values added with `box.add()` receive sequential integer keys, which can be accessed along with values inserted with explicit keys using the list-like `getAt(index)` method. ```Dart final box = Hive.box(); box.add('Lily'); box.put('key', 'Orchid'); print(box.getAt(0)); // Lily print(box.getAt(1)); // Orchid ``` -------------------------------- ### Defining Custom Object with Serialization Methods - Dart Source: https://github.com/isar/hive/blob/main/README.md Defines a standard Dart class `Bee` that includes a factory constructor `fromJson` for deserialization from a JSON map and a method `toJson` for serialization to a JSON map. These methods are required by Hive to handle non-primitive objects. ```Dart class Bee { Bee({required this.name, required this.role}); factory Bee.fromJson(Map json) => Bee( name: json['name'] as String, role: json['role'] as String, ); final String name; final String role; Map toJson() => { 'name': name, 'role': role, }; } ``` -------------------------------- ### Deleting All Entries from Hive Box using Clear in Dart Source: https://github.com/isar/hive/blob/main/README.md Shows how to remove all key-value pairs stored within a Hive box using the `box.clear()` method. This effectively empties the box while keeping the box itself available for future use. ```Dart box.clear(); ``` -------------------------------- ### Inserting Complex Data Types into Hive Box in Dart Source: https://github.com/isar/hive/blob/main/README.md Shows how to store complex types like Lists and Maps as values in a Hive box using the `box.put()` method. Hive supports storing various data structures as long as they are composed of supported primitive types or registered Hive objects. ```Dart box.put('friends', ['Buzzy', 'Stinger', 'Honey']); box.put('memories', {'firstFlight': 'Sunny Day', 'bestNectar': 'Rose'}); ``` -------------------------------- ### Accessing/Modifying Values by Index using Map Syntax in Hive Dart (List-like) Source: https://github.com/isar/hive/blob/main/README.md Shows how to access values stored in a Hive box using an integer index with the map-like syntax `box[index]`. It also demonstrates modifying the value at a specific index using `box[index] = value;`. Attempting to access or modify an index outside the current bounds of the box will result in an error. ```Dart final box = Hive.box(); box.add('Marigold'); print(box[0]); // Marigold box[0] = 'Daffodil'; box[1] = 'Bluebell'; // Error! This will get the bees in a whirl ``` -------------------------------- ### Error Opening Same Named Box with Different Generic Type in Hive Dart Source: https://github.com/isar/hive/blob/main/README.md Highlights a type safety constraint in Hive: once a box is opened with a specific generic type parameter (e.g., ``), subsequent attempts to open a box with the same name but a different generic type (e.g., ``) will result in an error to maintain data integrity and type consistency. ```Dart Hive.box(name: 'BeeTreasures'); // Error - We already have a String box! ``` -------------------------------- ### Enforcing Type Safety with Generic Hive Box in Dart Source: https://github.com/isar/hive/blob/main/README.md Explains how to apply type safety to a Hive box by specifying a generic type parameter when opening it (e.g., `Hive.box`). This restricts the box to storing only values of that specific type, preventing type errors at runtime as demonstrated by the commented-out invalid put operation. ```Dart final box = Hive.box(name: 'BeeTreasures'); box.put('DaisyDance', 'SweetNectarShake'); box.put('RoseRumba', 'GoldenPollenParty'); box.put('TulipTango', 777); // Error - You can't fool the bees! ``` -------------------------------- ### Deleting Single Entry from Hive Box in Dart Source: https://github.com/isar/hive/blob/main/README.md Explains how to remove a specific key-value pair from a Hive box using the `box.delete(key)` method. The method returns a boolean indicating whether the key was found and successfully deleted (`true`) or not (`false`). ```Dart final deleted = box.delete('lavenderHoney'); print('Honey eaten: $deleted'); // Honey eaten: true ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.