Database and Storage
Exporting and Importing Local Database Data in Flutter
By Pawan Kumawat • Published Dec 10, 2025 • 10 min read
1. Why Local Data Backup Matters
For local-first mobile applications that store user financial budgets, notes, or tasks on-device without a cloud backend, users need a reliable mechanism to back up their data or migrate records when switching to a new phone.
2. Building the Backup Export Engine
The code below serializes all SQLite table entries into a structured JSON map with version metadata, then writes the file to device storage:
backup_engine.dart
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'database_helper.dart';
class BackupEngine {
static Future<File> exportBackup() async {
final db = await DatabaseHelper.instance.database;
final notes = await db.query('notes');
final Map<String, dynamic> backupData = {
'version': 1,
'exportedAt': DateTime.now().toIso8601String(),
'tables': {
'notes': notes,
}
};
final jsonString = jsonEncode(backupData);
final directory = await getApplicationDocumentsDirectory();
final file = File('${directory.path}/organizer_backup.json');
return await file.writeAsString(jsonString);
}
static Future<bool> importBackup(String jsonContent) async {
try {
final Map<String, dynamic> data = jsonDecode(jsonContent);
if (data['version'] != 1) return false;
final db = await DatabaseHelper.instance.database;
final List<dynamic> notes = data['tables']['notes'] ?? [];
await db.transaction((txn) async {
await txn.delete('notes'); // Clear existing records
for (var note in notes) {
await txn.insert('notes', Map<String, dynamic>.from(note));
}
});
return true;
} catch (e) {
print("Import error: $e");
return false;
}
}
}
3. Conclusion
Using atomic transactions during database import prevents partial database corruption during backup restorations.