Reputation: 1
I'm working on a flutter project. I want to extract and add the database for backup, but I haven't been able to do it for days. I'm thinking about how I can do this. I wonder if I can do this. Is this possible? If not, should I do it? If this is not possible when using SQLite, what should I use?
I tried everything but I couldn't do it. If anyone has a sample project, please share it with me.
Upvotes: 0
Views: 183
Reputation: 4574
My understanding is that you just backup the files. The only trick to do this 'before' opening the database - as that locks the files.
Here is my backup script - note this won't work on web.
import 'dart:io';
import 'package:date_time_format/date_time_format.dart';
Future<void> backupDatabase(String pathToDatabase,
{required int version}) async {
final datePart =
DateTimeFormat.format(DateTime.now(), format: 'Y.j.d.H.i.s');
/// db file path with .bak and date/time/added
final backupPath =
'$pathToDatabase.$version.$datePart.bak';
final dbFile = File(pathToDatabase);
final backupFile = File(backupPath);
if (dbFile.existsSync()) {
await backupFile.writeAsBytes(await dbFile.readAsBytes());
print('''
Database backup completed successfully:
Original Size: ${dbFile.lengthSync()}
Backuped Size: ${backupFile.lengthSync()}
''');
} else {
print('Database file not found.');
}
}
Upvotes: 0