Skip to main content

How to use hive local db in Flutter


Hive local db in Flutter

 Hive is a lightweight and fast NoSQL database for Flutter that can be used for local storage in your Flutter applications. To use Hive in your Flutter app, follow these steps:


1. Add Hive to your `pubspec.yaml` file:

```yaml

dependencies:

  hive: ^2.0.4

```

2. Import the Hive package in your Dart code:


```dart

import 'package:hive/hive.dart';

```


3. Initialize Hive in your app. You should typically do this in your main function or `main.dart`:

```dart

void main() async {

  await Hive.initFlutter();

  // Other initialization code for your app

  runApp(MyApp());

}

```

4. Define your Hive data model by creating a Dart class that extends `HiveObject`. This class should represent the data you want to store in Hive. For example:

```dart

import 'package:hive/hive.dart';


@HiveType(typeId: 0)

class Person extends HiveObject {

  @HiveField(0)

  late String name;


  @HiveField(1)

  late int age;

}

```


In this example, we define a `Person` class with `name` and `age` fields. We annotate the class and fields with `@HiveType` and `@HiveField` annotations to specify how Hive should serialize and deserialize the data.


5. Initialize and open a Hive box where you can store your data. A box is similar to a table in a traditional database.


```dart

var box = await Hive.openBox<Person>('people');

```


In this example, we open a Hive box named 'people' to store instances of the `Person` class.


6. Perform CRUD (Create, Read, Update, Delete) operations on your data using the Hive box. Here are some examples:


   - **Create** a new person and save it to the box:


   ```dart

   var person = Person()

     ..name = 'John'

     ..age = 30;


   await box.add(person);

   ```


   - **Read** data from the box:


   ```dart

   var person = await box.get(0); // Get the first person in the box

   print(person.name); // Output: John

   ```


   - **Update** data:


   ```dart

   person.age = 31;

   await person.save(); // Save the updated person back to the box

   ```


   - **Delete** data:


   ```dart

   await person.delete(); // Delete the person from the box

   ```


7. Close the Hive box and Hive when you're done:


```dart

await box.close();

await Hive.close();

```


That's the basic overview of how to use Hive as a local database in a Flutter app. You can use Hive to store and retrieve data in a similar manner as you would with a traditional database, making it a convenient choice for local storage in Flutter applications.

Comments

Popular posts from this blog

How to write a code of Encode and Decode json data in Dart language

 Encode and decode JSON data in dart language import 'dart:convert'; void main() {   // Original data as a Dart map   Map<String, dynamic> originalData = {     'field1': 'value1',     'field2': 42,     'field3': true,   };   // Encode the Dart map to JSON string   String jsonString = jsonEncode(originalData);   print('Original JSON String:');   print(jsonString);   // Encode the JSON string to base64   String base64EncodedString = base64.encode(utf8.encode(jsonString));   print('\nBase64 Encoded String:');   print(base64EncodedString);   // Decode the base64 string to JSON string   String decodedJsonString = utf8.decode(base64.decode(base64EncodedString));   print('\nDecoded JSON String:');   print(decodedJsonString);   // Decode the JSON string to a Dart map   Map<String, dynamic> decodedData = jsonDecode(decodedJsonString);   print('\nDecoded Dart Ma...

About of Free Learning Tech Point

  Welcome to Free Learning Tech Point , where knowledge meets accessibility. Our platform is dedicated to providing high-quality educational resources and e-learning opportunities to learners around the world, completely free of charge. Our Mission: At Free Learning Tech Point, we believe that education is a fundamental right, and everyone should have access to valuable learning materials. Our mission is to break down barriers to education by offering a diverse range of courses, tutorials, and resources across various subjects and disciplines. What Sets Us Apart: - Free Access: Our commitment is to make learning accessible to all. No subscription fees, no hidden costs – just free, open access to knowledge.    - Quality Content: We curate and create content that is both engaging and informative. Whether you're a student, professional, or lifelong learner, our resources are designed to cater to various learning styles and levels. - Diverse Subjects: From tech and science...

Privacy Policy Of Free Learning Tech Point

  Thank you for visiting Free Learning Tech Point . You can use our website, services, and products with the awareness that this Privacy Policy describes how we gather, use, disclose, and protect your personal information. 1- Information We Collect: We may collect personal information that you provide directly to us, such as your name, email address, and any other information you choose to provide when using our Services. We may also collect non-personal information, such as aggregated data and usage patterns. 2- How We Use Your Information: We may use the information we collect for various purposes, including but not limited to: Providing and improving our Services. Responding to your inquiries and requests. Analyzing usage patterns and trends. Sending you updates, newsletters, and other communications. Personalizing your experience on our platform. 3- Cookies and Similar Technologies: We may use cookies and similar technologies to collect information about your interactions with...