Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

sqlite - Flutter sqflite open existing database

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...