Paramclasses Academy - Blog

Tutorials Details

←
Post 24 of 40
→

SQLite and Hive in Flutter: Local Database Storage for Beginners

SQLite and Hive in Flutter: Local Database Storage for Beginners

November 2, 2026

❖ SQLite and Hive in Flutter: Local Database Storage for Beginners

❖ Welcome to Param Classes!

Welcome to another practical lesson of Flutter App Development at Param Classes!

In previous tutorials, we learned how to store simple app preferences and local data using SharedPreferences. But what happens when an application needs to store hundreds or thousands of records, such as student details, product information, employee records, or transaction history?

For this purpose, Flutter developers can use local databases.

In this tutorial, we will understand two popular local database solutions: SQLite and Hive. We will learn their differences, installation, configuration, and basic CRUD operations with practical examples.

By the end of this tutorial, beginners will understand how to store, retrieve, update, and delete data inside a Flutter application.

✦ 1. What Is Local Database Storage in Flutter?

A local database stores application data directly on the user's device.

Unlike an online database, local storage does not require an internet connection for basic data operations.

For example, imagine you are developing a Student Management App. You want to save:

  • Student ID

  • Student Name

  • Mobile Number

  • Course Name

  • Registration Date

A local database can store these records so users can access them even when their device is offline.

Common uses of local databases:

  • Student Management Applications

  • Offline Notes Applications

  • Expense Tracker Applications

  • Shopping Cart Applications

  • Employee Management Systems

  • Inventory Management Applications

✦ 2. What Is SQLite in Flutter?

SQLite is a lightweight relational database. It stores information in tables containing rows and columns.

For example, a student table may look like this:

ID Name Course
1 Rahul Flutter
2 Amit PHP
3 Priya Python

SQLite is useful when your application needs structured data and SQL queries.

In Flutter, developers commonly use the sqflite package to work with SQLite databases.

Important SQLite features:

  • Stores structured data in tables.

  • Supports SQL queries.

  • Supports relationships between tables.

  • Works offline.

  • Supports insert, read, update, and delete operations.

✦ 3. How to Add SQLite in Flutter

First, open your Flutter project in Android Studio or VS Code.

Open the terminal and run:

flutter pub add sqflite
flutter pub add path

These packages help your Flutter application communicate with SQLite and manage the database file path.

You can check the official package documentation:

✦ 4. Create an SQLite Database

Inside your Flutter project, create a new file:

database_helper.dart

Add the following code:

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DatabaseHelper {
  static Database? _database;

  Future<Database> get database async {
    if (_database != null) {
      return _database!;
    }

    _database = await initDatabase();
    return _database!;
  }

  Future<Database> initDatabase() async {
    String path = join(
      await getDatabasesPath(),
      'student_database.db',
    );

    return await openDatabase(
      path,
      version: 1,
      onCreate: (db, version) async {
        await db.execute('''
          CREATE TABLE students(
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT,
            course TEXT
          )
        ''');
      },
    );
  }
}

Understanding the code:

  • DatabaseHelper manages database operations.

  • getDatabasesPath() gets the database storage directory.

  • openDatabase() opens or creates the database.

  • version: 1 defines the database version.

  • onCreate runs when the database is created for the first time.

  • CREATE TABLE creates a table named students.

✦ 5. Insert Student Data into SQLite

Now add an insert method inside the DatabaseHelper class:

Future<int> insertStudent(
  String name,
  String course,
) async {
  final db = await database;

  return await db.insert(
    'students',
    {
      'name': name,
      'course': course,
    },
  );
}

Explanation:

  • insertStudent() accepts student name and course.

  • db.insert() inserts the record into the students table.

  • The returned integer represents the inserted row ID.

✦ 6. Read Student Data from SQLite

To display saved student records, create this method:

Future<List<Map<String, dynamic>>> getStudents() async {
  final db = await database;

  return await db.query('students');
}

This method returns all records from the students table.

You can display the returned data using Flutter widgets such as ListView.builder.

✦ 7. Update and Delete Student Records

Update student information:

Future<int> updateStudent(
  int id,
  String name,
  String course,
) async {
  final db = await database;

  return await db.update(
    'students',
    {
      'name': name,
      'course': course,
    },
    where: 'id = ?',
    whereArgs: [id],
  );
}

Delete a student record:

Future<int> deleteStudent(int id) async {
  final db = await database;

  return await db.delete(
    'students',
    where: 'id = ?',
    whereArgs: [id],
  );
}

Notice the use of whereArgs. It safely passes values into the query instead of directly joining user input into SQL strings.

These four operations are known as CRUD:

  • Create — Insert new records.

  • Read — Retrieve saved records.

  • Update — Modify existing records.

  • Delete — Remove records.

✦ 8. What Is Hive in Flutter?

Hive is a lightweight local NoSQL database for Flutter and Dart applications.

Unlike SQLite, Hive does not require traditional tables and SQL queries. It stores data in boxes using keys and values.

For example:

name = "Rahul"
course = "Flutter"
mobile = "9876543210"

Hive is useful when you want a simple local storage solution without writing SQL queries.

Important Hive features:

  • Lightweight local database.

  • No SQL queries required.

  • Stores key-value data.

  • Supports custom objects using adapters.

  • Useful for offline applications.

  • Supports fast local data access.

✦ 9. How to Install Hive in Flutter

Open your terminal and run:

flutter pub add hive
flutter pub add hive_flutter

For this beginner example, we will store simple key-value data.

Official package documentation:

✦ 10. Initialize Hive Database

Open your main.dart file and initialize Hive before running the application.

import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Hive.initFlutter();

  await Hive.openBox('studentBox');

  runApp(const MyApp());
}

Explanation:

  • WidgetsFlutterBinding.ensureInitialized() prepares Flutter before asynchronous initialization.

  • Hive.initFlutter() initializes Hive.

  • Hive.openBox() opens a box named studentBox.

  • runApp() starts the Flutter application.

✦ 11. Insert and Read Data Using Hive

After opening the box, you can save data using keys and values.

Insert data:

var box = Hive.box('studentBox');

await box.put('name', 'Rahul');
await box.put('course', 'Flutter');
await box.put('mobile', '9876543210');

Read data:

var box = Hive.box('studentBox');

String name = box.get('name', defaultValue: '');

String course = box.get('course', defaultValue: '');

print(name);
print(course);

The put() method stores data, while get() retrieves data using its key.

✦ 12. Update and Delete Data in Hive

Update a record:

var box = Hive.box('studentBox');

await box.put('course', 'Advanced Flutter');

If the key already exists, Hive updates its value.

Delete a record:

var box = Hive.box('studentBox');

await box.delete('mobile');

Delete all records from a box:

await box.clear();

Be careful when using clear() because it removes all entries from that box.

✦ 13. SQLite vs Hive: What Is the Difference?

Both SQLite and Hive can store data locally, but they work differently.

Feature SQLite Hive
Database Type Relational NoSQL
Data Structure Tables Key-value boxes
Query Language SQL No SQL required
Relationships Supports table relationships Not traditional SQL relationships
Best Use Structured records Simple local data
CRUD SQL-style operations Box methods

Which one should beginners learn first?

Learn SQLite if you want to work with structured records, SQL queries, and relational databases.

Learn Hive if you want to understand simple local NoSQL storage and build lightweight offline features.

Both technologies are useful in Flutter development. The right choice depends on your application's requirements.

✦ 14. Common Mistakes Beginners Should Avoid

While working with local databases, beginners may face some common problems.

1. Forgetting database initialization

Always initialize Hive or open the SQLite database before using it.

2. Using the wrong box name

Make sure the box name used for reading and writing is the same as the one opened during initialization.

3. Not handling database version changes

When you modify an existing SQLite table structure, plan a database migration. Simply changing the CREATE TABLE statement will not update existing databases automatically.

4. Ignoring asynchronous operations

Database methods generally return Futures. Use async and await correctly.

5. Not testing CRUD operations

Always test insert, read, update, and delete operations before completing your application.

✦ 15. Practical Assignment for Beginners

Now it is time to practice!

Create a Student Management App using either SQLite or Hive.

Your application should include:

  1. Student Registration Form.

  2. Student Name input field.

  3. Mobile Number input field.

  4. Course selection.

  5. Save Student button.

  6. Student List screen.

  7. Edit Student option.

  8. Delete Student option.

Try to complete all four CRUD operations.

This practical project will help you understand how local database storage works in real Flutter applications.

❖ Conclusion

SQLite and Hive are two useful options for storing data locally in Flutter applications.

SQLite is suitable for structured records, SQL queries, and applications that require relational data. Hive provides a simple key-value approach for lightweight local storage.

At Param Classes, we focus on practical programming concepts that help beginners understand real application development. Keep practicing database operations and try building your own offline Student Management App.

In the next tutorial, we will learn how to connect a Flutter application to a REST API and fetch JSON data from a server.

Keep Learning, Keep Building with Param Classes!

←
Post 24 of 40
→