Flutter — Get data from a REST API and save locally in a Sqlite Database

Fábio Jansen
Dec 5, 2019 · 5 min read

Recently, when developing a Flutter application, I needed to get data from an external Api and write locally to Sqlite so that the data could be accessed without the need for an internet connection.

In this article, I will demonstrate the use of three famous Flutter libraries:
dio, path_provider and sqflite.

Note: To keep things simple, we will not use advanced concepts like Bloc and others.


1. Creating a new Flutter project:

Using your favorite code editor, start a new Flutter application. In this case, I will create an application called api_to_sqlite_flutter using the Visual Studio Code:

To make the process easier, we will delete the test/ folder because we will not deal with testing in this article.

Let’s also replace the entire contents of our lib/main.dart file with the following code:

2. Our REST API:

Our API, is a simple list of employees, which returns the following JSON:

If you wish, you can also use this API at:
https://demo8161595.mockable.io/employee

3. Creating the Employee Model:

We will use as our Model a Class called EmployeeModel that will be a representation of the information coming from our API. In this class, we will also create two very useful methods that will help us convert Json from our API into an Employee Class and also convert data from our Employee Class into a Json.

In our project, inside the “lib” folder create a folder called src/models and insert the code below:

  • In line 24 we have a method that takes a Map (json) and transforms it into an object of type Employee.
  • In line 32, we have a method that transforms an object of type Employee into a map (json) of type “key”: “value”.

For more information about Json serialization on Dart, visit:
https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51

4. Creating the Sqlite Database:

We will now create a class called DBProvider that will be responsible for creating our database, the employees table, and the database operations like create, insert and delete data.

We will use the Singleton pattern to create this class.

Singleton Pattern: We will use this pattern to make sure that we have only one instance of the created class.

More about singleton:

Inside our lib/src folder create a file called db_provider.dart and insert the content below:

  • Lines 1 to 6: We are importing the libraries needed for the database connection to work. These include sqflite (sqlite for flutter) and path_provider (which will give us access to our device’s internal storage).
  • Lines 9 to 22: We are creating a Database object and instantiating it if not initialized.
  • Lines 25 to 39: If the database is not initialized, we will create a database called employee_manager.db and also our “Employee” table.
  • Lines 42 to 66: The methods responsible for creating, deleting, and listing all records in our Employee table.

For More Details on Using the Sqlite Database on Flutter go to: https://medium.com/flutter-community/using-sqlite-in-flutter-187c1a82e8b

5. Method to get our API data and save to the local database:

With our database created, we can now save data coming from our API directly into our local Sqlite database.

For this task, we will use a Dart library called Dio, which will provide us with all the functionality needed to access the API.

Inside our lib / src / providers folder create a file called employee_api_provider.dart and insert the content below:

Here all “magic” happens:

  • In lines 6 to 14 we create an asynchronous method “getAllEmployees ()” of type Employee which when called executes an http / get call on our API (line 8) and for each object in the response (response.data), insert its contents directly into our database (line 12).

For more details on how to consume REST API on Flutter using Dio, go to: https://github.com/flutterchina/dio

With everything created, we can now add a new test page that will serve us to get the API data and display the information from our Database.

6. BONUS: Getting and Displaying Local Data on a Page:

First, let’s change our lib/src/main.dart file and set as our homepage a new page called HomePage (which we haven’t created yet).

  • At line 11 we are setting the home page to initialRoute and at line 12 we are defining that the home route will use our HomePage () page.

Inside our lib/src/ folder we will create a new folder called pages and inside it we will insert our home_page.dart

Just to get and display the data, we will create all the necessary logic within our home_page.dart.

Our page is structured as follows:

An AppBar with two buttons:

The first button will get the data from our API and insert it into our Sqlite database.

Clicking the button will call a _loadFromApi () method.

In this method we first set a local variable called isLoading = true so that a CircularProgressIndicator can be displayed simulating the loading of data.

After that we will execute our apiProvider.getAllEmployees () method which will get the data from our api and write it to our local database.

Next, we’ll add a 2-second Future.delayed to simulate data loading.

And finally, we will set the variable isLoading = false so that CircularProgressIndicator is hidden and instead a ListView is displayed that will get the data from the database and display it on the screen. (line 83)

The second button will delete all data from our Sqlite database.

7. Testing:

  • Click to play the video:

Source code: https://github.com/fabiojansenbr/flutter_api_to_sqlite

The Startup

Medium's largest active publication, followed by +566K people. Follow to join our community.

Fábio Jansen

Written by

Web/Mobile Developer | Cloud Consultant. Github: fabiojansenbr

The Startup

Medium's largest active publication, followed by +566K people. Follow to join our community.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade