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.
Asked
Active
Viewed 1,240 times
3
-
1Which kind of database? sqlite? firestore firebase? – Bruno Sponsorship Oct 21 '19 at 18:33
-
You can just store a boolean in shared preferences to check if you already have saved data in database if false save it and change that boolean to true so that it will not run again – Pedro Massango Oct 21 '19 at 20:31
-
@BrunoSponsorship I need to use my app offline, so sqlite is good variant. I also think that hive could be great variant, but I dont know if it accepts JOINS. – Ruslans Smolonskis Oct 23 '19 at 04:02
1 Answers
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