Open In App

Persist Data with SQLite in Flutter

Last Updated : 03 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

SQLite is an open-source computer database, it’s wont to store a piece of information, perform completely different operations like add, delete, and update. SQLite doesn’t need a server or backend code; all the info is saved to a computer file within the device, or we can say it’s native to storage. 

Demo Video:

Step-by-Step Implementation

Step 1: Installing the SQLite Plugin for Flutter

To be able to use SQLite in Flutter, you need to feature the plugin SQLite. Thus, to feature it, you wish to navigate to the pubspec.yaml file,

 

And add the SQLite and path dependency.

Dart
dependencies:
  cupertino_icons: ^1.0.2
  flutter:
    sdk: flutter
  path: ^1.8.0
  sqflite: ^2.0.0+4

Now run the below command in the terminal.

flutter pub get

Or

Run the below command in the terminal.

flutter pub add path sqflite


Step 2: File Structure

Follow below file structure below for better understanding.

file_structure


Step 2: Defining the Planet Model

Defining the model class in the data that needs to be stored. Our model class has the data members id, name, age, distancefromsun, and a constructor that initializes the data members.

planet.dart:

planet.dart
class Planets {
  late final int id;
  late final String name;
  late final int age;
  late final int distancefromsun;

  Planets({
    required this.id,
    required this.name,
    required this.age,
    required this.distancefromsun,
  });

  Planets.fromMap(Map<String, dynamic> result)
    : id = result["id"],
      name = result["name"],
      age = result["age"],
      distancefromsun = result["distancefromsun"];
  Map<String, Object> toMap() {
    return {
      'id': id,
      'name': name,
      'age': age,
      'distancefromsun': distancefromsun,
    };
  }
}


Step 3: Defining the Database Class

In Database class we have all the functions are implemented here, Database class has the following methods

  • initializedDB which gets the default data path using the getDatabasePath method of SQLite, opens the database in it using openDatabase method of SQLite, and then creates the table planets.
  • insertPlanets method takes the list of planets and inserts them into the table planets one by one.
  • retrievePlanets returns the list of planets.
  • deletePlanets delete the planet from the database by using the primary key id.

database.dart:

database.dart
import 'package:flutter_geeks/models/planet.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DataBase {
  Future<Database> initializedDB() async {
    String path = await getDatabasesPath();
    return openDatabase(
      join(path, 'planets.db'),
      version: 1,
      onCreate: (Database db, int version) async {
        await db.execute(
          "CREATE TABLE planets(id INTEGER PRIMARY KEY , name TEXT NOT NULL,age INTEGER NOT NULL,distancefromsun INTEGER NOT NULL)",
        );
      },
    );
  }

  // insert data
  Future<int> insertPlanets(List<Planets> planets) async {
    int result = 0;
    final Database db = await initializedDB();
    for (var planet in planets) {
      result = await db.insert('planets', planet.toMap(),
          conflictAlgorithm: ConflictAlgorithm.replace);
    }

    return result;
  }

  // retrieve data
  Future<List<Planets>> retrievePlanets() async {
    final Database db = await initializedDB();
    final List<Map<String, Object?>> queryResult = await db.query('planets');
    return queryResult.map((e) => Planets.fromMap(e)).toList();
  }

  // delete user
  Future<void> deletePlanet(int id) async {
    final db = await initializedDB();
    await db.delete(
      'planets',
      where: "id = ?",
      whereArgs: [id],
    );
  }
  // update data
Future<void> updatePlanet(Planets planet) async {
  final db = await initializedDB();
  await db.update(
    'planets',
    planet.toMap(),
    where: "id = ?",
    whereArgs: [planet.id],
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
}

}


Step 4: Defining Main File

  • In the main file, we call the main Function and run the runApp.
  • The initState method adds the data and calls the insertPlanets method.
  • And then we simply display the data on the user screen.

main.dart:

main.dart
import 'package:flutter/material.dart';
import './models/planet.dart';
import './services/database.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(Home());
}

class Home extends StatefulWidget {
  Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  late DataBase handler;

  Future<int> addPlanets() async {
    Planets firstPlanet = Planets(
      name: "Mercury",
      age: 24,
      id: 1,
      distancefromsun: 10,
    );
    Planets secondPlanet = Planets(
      name: "Venus",
      age: 31,
      id: 2,
      distancefromsun: 20,
    );
    Planets thirdPlanet = Planets(
      id: 3,
      name: 'Earth',
      age: 4,
      distancefromsun: 30,
    );
    Planets fourthPlanet = Planets(
      id: 4,
      name: 'Mars',
      age: 5,
      distancefromsun: 40,
    );

    List<Planets> planets = [
      firstPlanet,
      secondPlanet,
      thirdPlanet,
      fourthPlanet,
    ];
    return await handler.insertPlanets(planets);
  }

  Future<void> deletePlanet(int id) async {
    await handler.deletePlanet(id);
    setState(() {});
  }

  Future<void> editPlanet(Planets planet) async {
    await handler.updatePlanet(planet);
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    handler = DataBase();
    handler.initializedDB().whenComplete(() async {
      await addPlanets();
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Planets'),
          backgroundColor: const Color.fromARGB(255, 108, 38, 0),
          foregroundColor: Colors.white,
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: FutureBuilder(
            future: handler.retrievePlanets(),
            builder: (
              BuildContext context,
              AsyncSnapshot<List<Planets>> snapshot,
            ) {
              if (snapshot.hasData) {
                return ListView.builder(
                  itemCount: snapshot.data?.length,
                  itemBuilder: (BuildContext context, int index) {
                    final planet = snapshot.data![index];
                    return Card(
                      color: Colors.orange.shade100,
                      child: ListTile(
                        contentPadding: const EdgeInsets.all(8.0),
                        title: Text(planet.name),
                        subtitle: Text('Age: ${planet.age}'),
                        trailing: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            IconButton(
                              icon: const Icon(Icons.edit),
                              onPressed: () {
                                // Example edit: Update the planet's name
                                editPlanet(Planets(
                                  id: planet.id,
                                  name: '${planet.name} Updated',
                                  age: planet.age,
                                  distancefromsun: planet.distancefromsun,
                                ));
                              },
                            ),
                            IconButton(
                              icon: const Icon(Icons.delete),
                              onPressed: () {
                                deletePlanet(planet.id);
                              },
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                );
              } else {
                return const Center(child: CircularProgressIndicator());
              }
            },
          ),
        ),
        floatingActionButton: FloatingActionButton(
         backgroundColor: const Color.fromARGB(255, 108, 38, 0),
         foregroundColor: Colors.white,
          onPressed: () async {
            // Example add: Add a new planet
            await handler.insertPlanets([
              Planets(
                id: DateTime.now().millisecondsSinceEpoch,
                name: 'New Planet',
                age: 1,
                distancefromsun: 50,
              ),
            ]);
            setState(() {});
          },
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}


Complete Source Code

main.dart
import 'package:flutter/material.dart';
import './models/planet.dart';
import './services/database.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(Home());
}

class Home extends StatefulWidget {
  Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  late DataBase handler;

  Future<int> addPlanets() async {
    Planets firstPlanet = Planets(
      name: "Mercury",
      age: 24,
      id: 1,
      distancefromsun: 10,
    );
    Planets secondPlanet = Planets(
      name: "Venus",
      age: 31,
      id: 2,
      distancefromsun: 20,
    );
    Planets thirdPlanet = Planets(
      id: 3,
      name: 'Earth',
      age: 4,
      distancefromsun: 30,
    );
    Planets fourthPlanet = Planets(
      id: 4,
      name: 'Mars',
      age: 5,
      distancefromsun: 40,
    );

    List<Planets> planets = [
      firstPlanet,
      secondPlanet,
      thirdPlanet,
      fourthPlanet,
    ];
    return await handler.insertPlanets(planets);
  }

  Future<void> deletePlanet(int id) async {
    await handler.deletePlanet(id);
    setState(() {});
  }

  Future<void> editPlanet(Planets planet) async {
    await handler.updatePlanet(planet);
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    handler = DataBase();
    handler.initializedDB().whenComplete(() async {
      await addPlanets();
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Planets'),
          backgroundColor: const Color.fromARGB(255, 108, 38, 0),
          foregroundColor: Colors.white,
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: FutureBuilder(
            future: handler.retrievePlanets(),
            builder: (
              BuildContext context,
              AsyncSnapshot<List<Planets>> snapshot,
            ) {
              if (snapshot.hasData) {
                return ListView.builder(
                  itemCount: snapshot.data?.length,
                  itemBuilder: (BuildContext context, int index) {
                    final planet = snapshot.data![index];
                    return Card(
                      color: Colors.orange.shade100,
                      child: ListTile(
                        contentPadding: const EdgeInsets.all(8.0),
                        title: Text(planet.name),
                        subtitle: Text('Age: ${planet.age}'),
                        trailing: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            IconButton(
                              icon: const Icon(Icons.edit),
                              onPressed: () {
                                // Example edit: Update the planet's name
                                editPlanet(Planets(
                                  id: planet.id,
                                  name: '${planet.name} Updated',
                                  age: planet.age,
                                  distancefromsun: planet.distancefromsun,
                                ));
                              },
                            ),
                            IconButton(
                              icon: const Icon(Icons.delete),
                              onPressed: () {
                                deletePlanet(planet.id);
                              },
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                );
              } else {
                return const Center(child: CircularProgressIndicator());
              }
            },
          ),
        ),
        floatingActionButton: FloatingActionButton(
         backgroundColor: const Color.fromARGB(255, 108, 38, 0),
         foregroundColor: Colors.white,
          onPressed: () async {
            // Example add: Add a new planet
            await handler.insertPlanets([
              Planets(
                id: DateTime.now().millisecondsSinceEpoch,
                name: 'New Planet',
                age: 1,
                distancefromsun: 50,
              ),
            ]);
            setState(() {});
          },
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}
database.dart
import 'package:flutter_geeks/models/planet.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DataBase {
  Future<Database> initializedDB() async {
    String path = await getDatabasesPath();
    return openDatabase(
      join(path, 'planets.db'),
      version: 1,
      onCreate: (Database db, int version) async {
        await db.execute(
          "CREATE TABLE planets(id INTEGER PRIMARY KEY , name TEXT NOT NULL,age INTEGER NOT NULL,distancefromsun INTEGER NOT NULL)",
        );
      },
    );
  }

  // insert data
  Future<int> insertPlanets(List<Planets> planets) async {
    int result = 0;
    final Database db = await initializedDB();
    for (var planet in planets) {
      result = await db.insert('planets', planet.toMap(),
          conflictAlgorithm: ConflictAlgorithm.replace);
    }

    return result;
  }

  // retrieve data
  Future<List<Planets>> retrievePlanets() async {
    final Database db = await initializedDB();
    final List<Map<String, Object?>> queryResult = await db.query('planets');
    return queryResult.map((e) => Planets.fromMap(e)).toList();
  }

  // delete user
  Future<void> deletePlanet(int id) async {
    final db = await initializedDB();
    await db.delete(
      'planets',
      where: "id = ?",
      whereArgs: [id],
    );
  }
  // update data
Future<void> updatePlanet(Planets planet) async {
  final db = await initializedDB();
  await db.update(
    'planets',
    planet.toMap(),
    where: "id = ?",
    whereArgs: [planet.id],
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
}

}
planet.dart
class Planets {
  late final int id;
  late final String name;
  late final int age;
  late final int distancefromsun;

  Planets({
    required this.id,
    required this.name,
    required this.age,
    required this.distancefromsun,
  });

  Planets.fromMap(Map<String, dynamic> result)
    : id = result["id"],
      name = result["name"],
      age = result["age"],
      distancefromsun = result["distancefromsun"];
  Map<String, Object> toMap() {
    return {
      'id': id,
      'name': name,
      'age': age,
      'distancefromsun': distancefromsun,
    };
  }
}


Output:




Next Article

Similar Reads