Flutter database: What are they and how can you store in Flutter

Storing text in the database is one of the most current operations that we, as developers, are going to do. Sometimes we need to save the data from the server so the users can open the app and if there’s data already stored we can show that first, or if we want to implement an have an offline mode. Flutter database storing method is one of the great ways that can help you on persisting and retrieving database if needed.

Flutter database storing method

So, if writing an mobile app that needs to persist and query larger amounts of data on the local device, consider using a database instead of a local file or key-value store. In other words, no matter who you are or what you do, sooner or later you’re going to need to store data in your app and then retrieve it later. So now, we would like to introduce to you guys the definition of the Flutter database, as well as how can we store it in Flutter.

What is the Flutter database?

A Flutter database – like any other database ever – is an organized collection of data, which supports the storage and manipulation of data and accessed electronically from a computer system. We can organize data into rows, columns, tables, and indexes. It makes data management easy. We can store many things in the database, like name, age, picture, image, file, pdf, etc.
Flutter provides many packages to work with the database. The most used and popular packages are:

  • sqflite database: It allows to access and manipulate SQLite database.
  • Firebase database: It will enable you to access and manipulate the cloud database.

Related post: Flutter first application: How to create a simple app to know the basics

How can you store database in Flutter?

So now, let’s see step-by-step how we can store and fetch data in the Flutter.

Step 1. Create a new project

The first thing that we want you to do is creating a new project in Android Studio and add the dependencies in pubspec.yaml file. To do this, follow the codes below:

 dependencies:  
  flutter:  
    sdk: flutter  
  sqflite: any  
  path_provider: any

Some components that we would like to mention:

  • The sqflite package provides classes and functions to interact with the SQLite database.
  • The path_provider package provides functions to define the location of your database on the local system, such as TemporaryDirectory and ApplicationDocumentsDirectory.

Step 2. Create a model class for Flutter database

In this step, we have to define the data that needs to be stored before creating a table to store information. The following code explains it easily.

 class Book {  
  final int id;  
  final String title;  
  final int price;  
  Book({this.id, this.title, this.price});  
}  

Step 3. Open the database

Here, we need to open the connection to the database. It requires two steps:

  • Set the path to the database by using the getDtabasePath() method and combined it with the path package.
  • Use openDatabase() function to open the database.

It should go like this:

 // It allows to open the database and store the reference.  
final Future<Database> database = openDatabase(  
  join(await getDatabasesPath(), 'book_database.db'),  
);  

Step 4. Create a Flutter database table

In this step, we have to create a table that stores information about the books. Here, we are going to create a table named books, which contains the id, title, and price of the books. They are represented as three columns in the book table. So, here’s the example:

 final Future<Database> database = openDatabase(  
  join(await getDatabasesPath(), 'book_database.db'),  
  // When you create a database, it also needs to create a table to store books.  
  onCreate: (db, version) {  
    // Run the CREATE TABLE statement.  
    return db.execute(  
      "CREATE TABLE books(id INTEGER PRIMARY KEY, title TEXT, price INTEGER)",  
    );  
  },  
  // Set the version to perform database upgrades and downgrades.  
  version: 1,  
);  

Step 5. Insert a Book into the database. 

This step required a lot of things that you need to do for your Flutter database. Here, you have to store information on the table about the various books. Inserting a book into the table involves two steps:

  • Convert the Book into a Map
  • Uses insert() method

The following codes explain it more clearly:

 // Update the Book class.  
class Book{  
  final int id,  
  final String title;  
  final int price;  
  Book({this.id, this.title, this.price});  
  // It converts a Book into a Map. The keys correspond to the names of the columns in the database.  
  Map<String, dynamic> toMap() {  
    return {  
      'id': id,  
      'title': title,  
      'price': price,  
    };  
  }  
}  
Future<void> insertBook(Book book) async {  
  final Database db = await database;  
  await db.insert(  
    'books',  
    book.toMap(),  
    conflictAlgorithm: ConflictAlgorithm.replace,  
  );  
}  
// Create a Book and add it to the books table.  
final b1 = Book(  
  id: 0,  
  title: 'Let Us C',  
  price: 350,  
);  
await insertBook(b1); 

Step 6. Retrieve the list of books. 

Now, we have stored the book into the Flutter database, and you can use a query to retrieve a particular book or list of all books. It involves two steps:

  • Run a query that returns List<Map>.
  • Convert the List<Map> into the List<Book>.

You can see the following code to understand it easily in Flutter database.

 // This method retrieves all the books from the books table.  
Future<List<Book>> books() async {  
  final Database db = await database;  
  // Use query for all Books.  
  final List<Map<String, dynamic>> maps = await db.query('maps');  
  return List.generate(maps.length, (i) {  
    return Book(  
      id: maps[i]['id'],  
      title: maps[i]['title'],  
      price: maps[i]['price'],  
    );  
  });  
}  
// It prints all the books.  
print(await books());

Step 7. Update a Book in the Flutter database

You can use an update() method to update the book that you want. It involves two steps:

  • Convert Book into the Map.
  • Then, use where clause to update the book.

You can see the following code to understand it.

 Future<void> updateBook(Book book) async {  
  final db = await database;  

  // Update the given Book.  
  await db.update(  
    'books',  
    book.toMap(),  
    // It ensure the matching id of a Book.  
    where: "id = ?",  
    whereArgs: [book.id],  
  );  
}  
// Update b1 price.  
await updateBook(Book(  
  id: 0,  
  title: 'Let Us C',  
  price: 420,  
));  
// Print the updated results.  
print(await books());  

Step 8. Delete a Book from the Flutter database

You can use the delete() method to delete the database. For this, you need to make a function that takes an id and delete the database of the matching id. Let’s see the complete code to understand how we can create a database file with sqflite plugin. For this, create a new Flutter project and the sqflite and path package into the pubspec.yaml file. Next, create a new file into the lib folder and insert the following code in this file.

 Future<void> deleteBook(int id) async {  
  final db = await database;  
  // This function removes books from the database.  
  await db.delete(  
    'books',  
    where: "id = ?",  
    whereArgs: [id],  
  );  
}  

Final words

And that should be it! Here’s the definition of Flutter database, as well as how they can store in Flutter. All in all, Flutter apps can make use of the SQLite databases via the sqflite plugin available in the pub. This recipe demonstrates the basics of using sqflite to insert, read, update, and remove data about various components. So, use it wisely, and your store will become much more perfect.
We – ArrowHiTech is proud to be one of the most famous IT companies all around the world. With over 12 years of experience, we can provide the best Flutter app development services for your business.

Tags

Share