How can open existing db from assets with flutter and sqflite? I read this guide : https://github.com/tekartik/sqflite/blob/master/doc/opening_db.md#preloading-data
But my app shows 'not found table' error Thanks.
The Opening an asset database guide explains the steps you have to do to bundle and open a pre-existing SQLite database inside your Flutter app:.
First, you must edit your pubspec.yaml
configuration to refer to your pre-existing SQLite database file, so that it gets bundled into your app when the app is built. In this following example, we will assume the file exists at assets/demo.db
under your Flutter app directory:
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/demo.db
Next, in your app initialization, you will need to copy the bundled file data into a usable location, because the bundled resource itself can't be directly opened as a file on Android.
The sqflite.getDatabasesPath()
function will return the directory to use for this. This will typically be something like /data/data/org.example.myapp/databases/
on Android. With this in hand, you can load the byte data from your bundled asset and create the app's writable database file, here named app.db
:
// Construct the path to the app's writable database file:
var dbDir = await getDatabasesPath();
var dbPath = join(dbDir, "app.db");
// Delete any existing database:
await deleteDatabase(dbPath);
// Create the writable database file from the bundled demo database file:
ByteData data = await rootBundle.load("assets/demo.db");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(dbPath).writeAsBytes(bytes);
Finally, you can open the created database file on app startup:
var db = await openDatabase(dbPath);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With