Connecting SQLite Database to Mobile App with Flutter and Dart

To connect a SQLite database to a mobile app built with Flutter and Dart, you can follow these steps:

Add Dependencies

Add the sqflite and path_provider dependencies to your pubspec.yaml file. sqflite is a Flutter plugin for SQLite, and path_provider is used to get the directory for storing the database file.

dependencies:
  flutter:
    sdk: flutter
  sqflite: ^2.0.0
  path_provider: ^2.0.2

Run flutter pub get to install the packages.

Create a Database Helper Class

Create a helper class to interact with the SQLite database. This class will handle tasks such as creating the database, CRUD operations, etc. Below is a basic example of a database helper class:

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

class DatabaseHelper {
  static final DatabaseHelper _instance = DatabaseHelper._internal();
  static late Database _database;

  DatabaseHelper._internal();

  factory DatabaseHelper() => _instance;

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

  Future<Database> _initDatabase() async {
    var directory = await getApplicationDocumentsDirectory();
    var path = join(directory.path, 'your_database.db');
    return await openDatabase(path, version: 1, onCreate: _onCreate);
  }

  Future<void> _onCreate(Database db, int version) async {
    await db.execute('''
      CREATE TABLE your_table (
        id INTEGER PRIMARY KEY,
        name TEXT,
        age INTEGER
      )
    ''');
  }

  Future<int> insertData(Map<String, dynamic> data) async {
    Database db = await database;
    return await db.insert('your_table', data);
  }

  Future<List<Map<String, dynamic>>> getData() async {
    Database db = await database;
    return await db.query('your_table');
  }

  // Implement other CRUD operations as needed
}

Use the Database Helper Class

You can now use the methods defined in the DatabaseHelper class to interact with the SQLite database in your Flutter app. For example, you can insert data into the database when a button is pressed or display data from the database in a list view.

Handle Asynchronous Operations

Since database operations are asynchronous, make sure to handle them properly using async and await keywords or using .then() and .catchError() methods.

Run Your App

After implementing the database functionality, run your Flutter app to test the SQLite database integration.

By following these steps, you can connect a SQLite database to your mobile app built with Flutter and Dart and perform various database operations within your app.


Similar Articles