3

Is there any example of pre-populated database usage in Flutter? I don't need CRUD example. At this point I just need to read data from database. I am new to Flutter so step by step tutorial would be nice.

1 Answers1

2

You can bundle your app with your pre-populated sqlite database in your assets folder. And then on the first run copy the database from assets to your app's working directory. The following code sample shows one way to do it (print statements are just to show what is happening where):

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

Future<Database> initDatabase() async {
    var databasesPath = await getDatabasesPath();
    var path = join(databasesPath, "app.v1.db");

    // Check if the database exists
    var exists = await databaseExists(path);

    if (!exists) {
      // Should happen only the first time you launch your application
      print("Creating new copy from asset");

      // Make sure the parent directory exists
      try {
        await Directory(dirname(path)).create(recursive: true);
      } catch (e) {
        print(e.toString());
      }

      // Copy from asset
      ByteData data = await rootBundle.load(join("assets", "prepopulated.db"));
      List<int> bytes =
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

      // Write and flush the bytes written
      await File(path).writeAsBytes(bytes, flush: true);
      print("Database created successfully");
    } else {
      print("Opening existing database");
    }

    // open the database
    return await openDatabase(path, version: "1", readOnly: false);
}
moshfiqur
  • 2,065
  • 3
  • 24
  • 27