Open In App

Persist Data with SQLite in Flutter

Improve
Improve
Like Article
Like
Save
Share
Report

SQLite is an open supply computer database, it’s wont to produce a piece of information, perform completely different operations like add, delete, and take away knowledge. SQLite doesn’t need a server or backend code, all the info is saved to a computer file within the device, or we will say it’s native to storage. 

Installing SQLite Plugin to Flutter

To be able to use SQLite in Flutter, you wish 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 you can start using SQLite in the Flutter project!

Defining the Planet Model

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

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
    };
  }
}


Defining the Database Class

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

  • initializedDB which is actually getting the default data path using getDatabasePath method of SQLite, open database into it using openDatabase method of SQLite, and then create the table planets.
  • insertPlanets method takes the list of planets and inserts in 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.

Dart




import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'model.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],
    );
  }
}


Defining Main File

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

Dart




import 'package:flutter/material.dart';
import 'package:sqliteimplementation/model.dart';
import 'package:sqliteimplementation/service.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);
  }
 
  @override
  void initState() {
    super.initState();
    handler = DataBase();
    handler.initializedDB().whenComplete(() async {
      await addPlanets();
      setState(() {});
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: 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) {
                  return Card(
                    child: ListTitle(
                      contentPadding: const EdgeInsets.all(8.0),
                      title: Text(snapshot.data![index].name),
                      subtitle: Text(snapshot.data![index].age.toString()),
                    ),
                  );
                },
              );
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }
}


Output:

Output

 



Last Updated : 09 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads