how to use SQlite in flutter for local database storage

How to Use SQLite in Flutter for Local Database Storage

Introduction

Many applications need to store information such as user notes, tasks, products, and records.

For example, imagine building a notes application. Users should be able to create notes, close the app, and return later to find their saved notes.

SharedPreferences is useful for small settings, but it is not designed for managing large collections of structured records.

A better option is SQLite, a lightweight database that can store information directly on a device.

In this tutorial, you will learn how SQLite works in Flutter and how to create a simple notes application that can save, display, and delete notes.

1. What Is SQLite?

SQLite is a small relational database engine that stores information in a database file.

Unlike an online database, SQLite can work locally on a device without requiring an internet connection.

It is commonly used for applications that need to store structured information.

Examples include:

- Notes applications.
- To-do list applications.
- Offline shopping catalogues.
- Personal finance applications.
- Reading applications.
- Applications that need temporary offline records.

2. Why Use SQLite in Flutter?

SQLite offers several advantages:

1. Offline access: Users can access locally stored information without an internet connection.

2. Structured storage: Information can be organized into tables with rows and columns.

3. Data management: You can insert, retrieve, update, and delete records.

4. Lightweight: SQLite does not require a separate database server.

5. Useful for real projects: It can support many types of mobile applications.

3. Install the Required Flutter Packages

For this tutorial, we will use two packages:

- "sqflite" for SQLite database operations.
- "path" for safely building the database file path.

Open your Flutter project terminal and run:

flutter pub add sqflite path

These packages are commonly used for SQLite on Android and iOS. The example below is intended for those mobile platforms; web and desktop projects need an appropriate SQLite implementation.

4. Create a Database Helper

A database helper keeps database operations separate from the user interface.

Inside your "lib" folder, create a file named:

"database_helper.dart"

Add this code:

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

class DatabaseHelper {
  static final DatabaseHelper instance =
      DatabaseHelper._init();

  static Database? _database;

  DatabaseHelper._init();

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

    _database = await _initDB('notes.db');

    return _database!;
  }

  Future<Database> _initDB(String fileName) async {
    final dbPath = await getDatabasesPath();

    final path = join(dbPath, fileName);

    return await openDatabase(
      path,
      version: 1,
      onCreate: _createDB,
    );
  }

  Future<void> _createDB(Database db, int version) async {
    await db.execute('''
      CREATE TABLE notes (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        content TEXT NOT NULL
      )
    ''');
  }

  Future<int> addNote(
    String title,
    String content,
  ) async {
    final db = await instance.database;

    return await db.insert(
      'notes',
      {
        'title': title,
        'content': content,
      },
    );
  }

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

    return await db.query(
      'notes',
      orderBy: 'id DESC',
    );
  }

  Future<int> updateNote(
    int id,
    String title,
    String content,
  ) async {
    final db = await instance.database;

    return await db.update(
      'notes',
      {
        'title': title,
        'content': content,
      },
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  Future<int> deleteNote(int id) async {
    final db = await instance.database;

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

5. Understand the Database Code

Let's understand the important parts.

Creating the database

_initDB('notes.db');

This creates or opens a database file named "notes.db".

Creating a table

CREATE TABLE notes (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT NOT NULL,
  content TEXT NOT NULL
)

The table contains three columns:

- "id": A unique number for each note.
- "title": The note title.
- "content": The note details.

Adding information

The "addNote()" method inserts a new note into the database.

Reading information

The "getNotes()" method retrieves saved notes.

Updating information

The "updateNote()" method changes an existing note.

Deleting information

The "deleteNote()" method removes a note using its ID.

Notice that the update and delete operations use "whereArgs". Parameterized queries help protect database operations from SQL injection.

6. Build a Simple Notes Application

Now let's create the user interface.

Open "lib/main.dart" and add:

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

void main() {
  runApp(const NotesApp());
}

class NotesApp extends StatelessWidget {
  const NotesApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'SQLite Notes',
      theme: ThemeData(
        colorSchemeSeed: Colors.blue,
        useMaterial3: true,
      ),
      home: const NotesPage(),
    );
  }
}

class NotesPage extends StatefulWidget {
  const NotesPage({super.key});

  @override
  State<NotesPage> createState() => _NotesPageState();
}

class _NotesPageState extends State<NotesPage> {
  final titleController = TextEditingController();
  final contentController = TextEditingController();

  List<Map<String, dynamic>> notes = [];

  @override
  void initState() {
    super.initState();
    loadNotes();
  }

  Future<void> loadNotes() async {
    final data = await DatabaseHelper.instance.getNotes();

    if (!mounted) return;

    setState(() {
      notes = data;
    });
  }

  Future<void> addNote() async {
    final title = titleController.text.trim();
    final content = contentController.text.trim();

    if (title.isEmpty || content.isEmpty) return;

    await DatabaseHelper.instance.addNote(
      title,
      content,
    );

    titleController.clear();
    contentController.clear();

    await loadNotes();
  }

  Future<void> deleteNote(int id) async {
    await DatabaseHelper.instance.deleteNote(id);

    await loadNotes();
  }

  @override
  void dispose() {
    titleController.dispose();
    contentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('My SQLite Notes'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(
              controller: titleController,
              decoration: const InputDecoration(
                labelText: 'Note title',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 10),
            TextField(
              controller: contentController,
              maxLines: 3,
              decoration: const InputDecoration(
                labelText: 'Write your note',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 10),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: addNote,
                child: const Text('Save Note'),
              ),
            ),
            const SizedBox(height: 20),
            const Text(
              'Saved Notes',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 10),
            Expanded(
              child: notes.isEmpty
                  ? const Center(
                      child: Text('No notes saved yet.'),
                    )
                  : ListView.builder(
                      itemCount: notes.length,
                      itemBuilder: (context, index) {
                        final note = notes[index];

                        return Card(
                          child: ListTile(
                            title: Text(note['title']),
                            subtitle: Text(note['content']),
                            trailing: IconButton(
                              icon: const Icon(
                                Icons.delete,
                                color: Colors.red,
                              ),
                              onPressed: () {
                                deleteNote(note['id']);
                              },
                            ),
                          ),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }
}

7. Test Your SQLite Application

Run your Flutter application on an Android emulator or supported Android device.

Try these steps:

1. Open the application.
2. Enter a note title.
3. Write some note details.
4. Press Save Note.
5. Check that the note appears in the list.
6. Close and reopen the application.
7. Check that your note is still available.
8. Press the delete icon to remove a note.

The application should save your notes in its local SQLite database.

8. How to Update a Note

Our database helper already contains an "updateNote()" method.

You can call it when a user edits an existing note:

await DatabaseHelper.instance.updateNote(
  noteId,
  'Updated Title',
  'Updated note content',
);

Here, "noteId" should be the ID of the note being edited.

After updating, reload the notes list to display the latest information.

9. SQLite vs SharedPreferences

Both SQLite and SharedPreferences can store information locally, but they serve different purposes.

Feature| SharedPreferences| SQLite
Simple settings| Excellent| Possible
Structured records| Not suitable| Excellent
Multiple tables| No| Yes
Search and filtering| Limited| Yes
Offline storage| Yes| Yes
Complex relationships| No| Yes

Use SharedPreferences for simple settings and SQLite when you need to manage structured records.

10. Important Database Security Tips

When building real applications:

- Do not store plain-text passwords in your database.
- Use parameterized database queries.
- Validate information before saving it.
- Consider database backups where appropriate.
- Plan database version upgrades when your table structure changes.
- Protect sensitive information using suitable encryption and secure-storage solutions.

Also remember that local SQLite data normally belongs to the device where it was saved. If users need to access the same records on multiple devices, you will need a backend synchronization system.

11. Practical Project

Try building your own offline task management application using SQLite.

Your application should allow users to:

- Add new tasks.
- View saved tasks.
- Edit existing tasks.
- Delete completed tasks.
- Keep their tasks after restarting the app.

This project will help you understand how real Flutter applications manage local information.

Conclusion

SQLite is a useful database technology for Flutter developers who want to build applications that can store structured information locally.

In this tutorial, you learned how to install SQLite packages, create a database, create a table, insert records, retrieve information, update records, and delete data.

Keep practising these database operations because they are important skills for building professional mobile applications.

CHIO BLOG App Development Academy: Learn to Code, Build Real Apps, and Create Your Future.

Comments

Popular posts from this blog

how to become an AI engineer in 2026

10 Blogging mistake bloginers should avoid

how to check waec result 2026