Open In App

Persist Data with SQLite in Flutter

Last Updated : 14 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

SQLite is an open-source computer database used to store pieces of information and perform various operations, such as adding, deleting, and updating. SQLite doesn't need a server or backend code; all the data is saved to a computer file within the device, or we can say it is stored locally. 

Demo Video

Step-by-Step Implementation

Step 1: Create a new Flutter Application

Create a new Flutter application using the command Prompt. To create a new app, write the following command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter.

Step 2: Adding the Dependency

To add the dependency to the pubspec.yaml file, add path and sqflite in the dependencies part of the pubspec.yaml file, as shown below:

Dart
dependencies:
  cupertino_icons: ^1.0.2
  flutter:
    sdk: flutter
  path: ^1.9.1
  sqflite: ^2.4.2

Now, run the command below in the terminal.

flutter pub get

Or

Run the command below in the terminal.

flutter pub add path sqflite

Step 3: File Structure

Follow the file structure below for better understanding.

file_structure


Step 4: Defining the Planet Model

Define the model class for the data that needs to be stored. This model class has data members like 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 5: Defining the Database Class

The Database class contains all the following functions,

  • initializedDB, which gets the default data path using the getDatabasePath method of SQLite, opens the database in it using the openDatabase method of SQLite, and then creates the table planets.
  • insertPlanets method takes the list of planets and inserts them into the planets table one by one.
  • retrievePlanets returns the list of planets.
  • deletePlanets method deletes a planet from the database by using its 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 6: 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.
  • We then 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