Creating an sqflite database

Let's create a new Flutter project from your editor. We can call it shopping. Follow the steps given here:

  1. As sqflite is a package, the first step to perform in order to be able to use it in our project is adding the dependency in the pubspec.yaml file.

In order to find the latest version of the dependency, please visit https://pub.dev/packages/sqflite. The dependencies that we are going to use in this project are shown in the following code block:

dependencies:
flutter:
sdk: flutter
sqflite: ^1.2.0
path: ^1.6.4
  1. In the lib folder, create a subfolder called util. Here, we'll create a new file: dbhelper.dart. This file will contain the methods to create the database, and to retrieve and write data.
  2. At the top of the file, we'll import sqflite.dart and path.dart. path.dart is a library that allows you to manipulate file paths. This is useful here, as each platform (iOS or Android) saves the file in different paths. By using the path.dart library, we don't need to know how files are saved in the current operating system, and we can still access the database using the same code. Import the path and sqflite libraries at the top of the dbhelper.dart file, as follows:
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
  1. Create a class that can be called from other parts of our code: quite predictably, we can call it DbHelper, as shown in the following snippet: 
class DbHelper {}
  1. Inside the class, create two variables: an integer called version and a database called dbversion contains a number that represents the version of the database, which at the beginning is 1. This will make it easier to update the database when you need to change something in its structure. db will contain the SQLite database itself. Place the two declarations at the top of the DbHelper class, like this:
final int version = 1;
Database db;
  1. Create a method that will open the database if it exists, or create it if it doesn't; we can call it openDb.
  2. As database operations may take some time to execute, especially when they involve dealing with a large quantity of data, they are asynchronous. Therefore, the openDb function will be asynchronous and return a Future of type Database. Let's place the following code at the end of the DbHelper class:
Future<Database> openDb() async {}
  1. Inside the function, first, we need to check whether the db object is null. This is because we want to avoid opening a new instance of the database unnecessarily. In the openDb() method, let's add the following code:
if (db == null) {}
  1. If db is null, we need to open the database. The sqflite library has an openDatabase method. We'll set three parameters in our call: the path of the database to be opened, the version of the database, and the onCreate parameter. The onCreate parameter will only be called if the database at the path specified is not found, or the version is different. The code for this is shown in the following block:
if (db == null) {
db = await openDatabase(join(await getDatabasesPath(),
'shopping.db'),
onCreate: (database, version) {
database.execute(
'CREATE TABLE lists(id INTEGER PRIMARY KEY, name TEXT,
priority
INTEGER)');
database.execute(
'CREATE TABLE items(id INTEGER PRIMARY KEY,
idList INTEGER, name TEXT, quantity TEXT,
note TEXT, ' + 'FOREIGN KEY(idList)
REFERENCES lists(id))');
}, version: version);
}

The function inside the onCreate parameter takes two values: a database and a version. In the function, we call the execute() method, which performs raw SQL queries in a database. Here, we are calling it twice: the first time to create the lists table, and the second time for the items table. 

You may notice that we are using only two data types: INTEGER and TEXT.

In SQLite, there are only five data types: NULL, INTEGER, REAL, TEXT, and BLOB. Note that there are no Boolean or Date data types.

The quantity field of the items table is a TEXT and not a number because we want to allow the user to insert the measure as well, such as "5 lbs" or "2 kg".

When an integer field is called id and is a primary key, when you provide NULL while inserting a new record, the database will automatically assign a new value, with an auto-increment logic. So, if the greatest ID is 10, the next record will automatically take 11.
  1. Finally, let's return the database at the end of the openDb() method, like this:
return db;

To sum up, what happens here is that if a database named shopping.db exists and has a version number of 1, the database gets opened. Otherwise, it gets created.

Let's check if everything works as expected, next. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.74.211