Flutter Sqflite database Backup & Restore (import/export DB)
While using sqflite package in flutter for local database, there comes scenarios where we may need to backup and restore the database.
As for an example, suppose the user wants to uninstall your app (which is functioning in sqflite package) and install it in a newer device. On doing so he even wants to somehow use the database stored in the previous device. Simply saying he wants an export/import DB feature in the app which makes his work quite very easier.
In this tutorial, we will be learning how we can import/export our app local sqflite DB.
- First thing first, we need to add the following dependencies in our pubspec.yaml file.
Read the permission_handler package setup instructions nicely (from here) and configure your app, otherwise you may face problems while running.
For Android (permission_handler setup instructions)
i. Make sure you set the compileSdkVersion
in your "android/app/build.gradle" file to 31:
android {
compileSdkVersion 31
...
}
ii. Add permissions to your AndroidManifest.xml
file. In general, it’s sufficient to add permission only to the main
version.
//----Add below lines----------------------<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><applicationandroid:requestLegacyExternalStorage="true" //------And this line
2. (This is for demo DB you can continue with your own database).
Paste the following link example code into a new file called lib/db_test.dart
. This is from the flutter documentation on how to use sqflite package.
And run the file lib/db_test.dart
only as shown in the image below. Then we will have our database created in our app. (You can continue with your own database, this is for demo purpose).
3. Add some buttons for import/ export feature as in the example below and paste the following code in your buttons.
And hopefully you have added import/export database feature in your app.
Congrats!!! Give a clap, clap, clap
If you need the project link, checkout from here.