The Wayback Machine - https://web.archive.org/web/20240609011544/https://www.geeksforgeeks.org/persist-data-with-sqlite-in-flutter/
Open In App

Persist Data with SQLite in Flutter

Last Updated : 09 Nov, 2022
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

 



Similar Reads

Flutter - Sharing Data Among Flutter Pages
In this article, we are going to find the solution for the problem statement "Import/send data from one page to another in flutter". Before going into the topic, there are some pre-requisites. Pre-requisites:Basics of dart programming language.Setting up Flutter in VS code or Setting up Flutter in Android Studio.Creating first flutter app | Hello W
4 min read
Is Flutter Worth Learning? Top 7 Reasons to Learn Flutter
In today's era, the usage of smartphones has increased exponentially and so has the use of mobile applications and websites. Meanwhile, considering future career prospects, learning web development and mobile app development is strongly recommended for all individuals. And when we come to mobile app development, there are two most-popular open-sour
5 min read
Flutter Quill - Rich Text Editor in Flutter Application
This post will explain how to integrate a rich text editor into your Flutter application so that it may enable rich text editing. There are many more things we can do with Flutter Quill, but they can get a little involved. The example below is a pretty basic demonstration of what we mean. Let's first discuss what flutter quill is and why we need it
5 min read
Flutter - Animated AlertDialog in Flutter
Animating an AlertDialog in Flutter involves using the Flutter animations framework to create custom animations for showing and hiding the dialogue. In this article, we are going to add an animation to an AlertDialog. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.
4 min read
Flutter - Different Types of Loading using Flutter EasyLoading
Flutter applications involve incorporating loading indicators to provide users with feedback during background operations. Flutter has a package for simplifying the process named flutter_easyloading package. This package easiest way to integrate loading indicators with various styles. In this article, we will implement different types of loading in
5 min read
Retrieve Data From TextFields in Flutter
In this article, we'll learn how to retrieve data from TextFields. TextField() widget is the most common widget used in flutter apps to take user input. We'll talk about two major methods used to extract text from TextField. Using Variables:The TextField widget has various callback properties through which we can extract text. Majorly, onChanged is
4 min read
Flutter - Updating Data on the Internet
In today's world, most applications heavily rely on fetching and updating information from the servers through the internet. In Flutter, such services are provided by the http package. In this article, we will explore the same. To update the data on the Internet follow the below steps: Import the http packageUpdate data t using the http packageConv
5 min read
Flutter - Fetching Data From the Internet
In today's world, most applications heavily rely on fetching information from the servers through the internet. In Flutter, such services are provided by the http package. In this article we will explore the same. To fetch data from the internet follow the below steps: Import the http packageMake a network request using the http packageConvert the
3 min read
Flutter - Deleting Data On The Internet
In this article, we will explore the process of deleting data on the internet. To, do so we need to follow 3 crucial steps: Import the http packageDelete the data on the serverUpdate the screen after deletion Now, we will explore them in detail. Importing The http Package: To install the http package use the below command in your command prompt: pu
3 min read
Flutter - Sending Data To The Internet
Interacting with the Internet is crucial for most apps to function. In Flutter the http package is used to send the data to the internet. In this article, we will explore the same topic in detail. To send data to the internet through your application follow the below steps: Import the http packageSend data to the server through the http packageChan
4 min read