Skip to main content

How to use sqflite local db in Flutter

 

SQLite local db in Flutter

To use the `sqflite` package for local database storage in your Flutter application, you can follow these steps:


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


```yaml

dependencies:

  sqflite: ^x.x.x # Use the latest version of sqflite

```


Replace `^x.x.x` with the latest version of the `sqflite` package available at the time you are adding it to your project.


2. Import the `sqflite` package and other necessary packages in your Dart code:


```dart

import 'package:flutter/material.dart';

import 'package:sqflite/sqflite.dart';

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

```


3. Create a database helper class to manage your SQLite database. Here's a basic example of a database helper class:


```dart

class DatabaseHelper {

  static final DatabaseHelper _instance = DatabaseHelper._internal();


  factory DatabaseHelper() => _instance;


  DatabaseHelper._internal();


  late Database _database;


  Future<void> initializeDatabase() async {

    final databasePath = await getDatabasesPath();

    final pathToDatabase = path.join(databasePath, 'my_database.db');


    _database = await openDatabase(

      pathToDatabase,

      version: 1,

      onCreate: (db, version) async {

        // Create tables and define schema here

        await db.execute('''

          CREATE TABLE IF NOT EXISTS users (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            name TEXT,

            email TEXT

          )

        ''');

      },

    );

  }


  Future<void> insertUser(Map<String, dynamic> userData) async {

    await _database.insert('users', userData);

  }


  Future<List<Map<String, dynamic>>> getUsers() async {

    return await _database.query('users');

  }


  Future<void> updateUser(int id, Map<String, dynamic> userData) async {

    await _database.update('users', userData, where: 'id = ?', whereArgs: [id]);

  }


  Future<void> deleteUser(int id) async {

    await _database.delete('users', where: 'id = ?', whereArgs: [id]);

  }

}

```


In this example, the `DatabaseHelper` class creates and manages a SQLite database with a table named 'users'. You can customize this class to match your data model and database schema.


4. Initialize and open the database in your app, typically in the `main` function or `main.dart` file:


```dart

void main() async {

  WidgetsFlutterBinding.ensureInitialized();

  final databaseHelper = DatabaseHelper();

  await databaseHelper.initializeDatabase();

  

  runApp(MyApp());

}

```


5. Use the `DatabaseHelper` methods to interact with the database in your app. For example, you can insert, retrieve, update, and delete data as needed.


```dart

final databaseHelper = DatabaseHelper();


// Insert a user

await databaseHelper.insertUser({'name': 'John Doe', 'email': 'john@example.com'});


// Retrieve users

final users = await databaseHelper.getUsers();


// Update a user

await databaseHelper.updateUser(1, {'name': 'Updated Name', 'email': 'updated@example.com'});


// Delete a user

await databaseHelper.deleteUser(1);

```


6. Ensure that you close the database when your app is done using it:


```dart

await databaseHelper.close();

```


These are the basic steps for using the `sqflite` package to create and manage a local SQLite database in your Flutter app. You can customize the database schema and operations to suit your application's specific needs.

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...