Sub topic 2
Storing Data: Files, Secrets and SQLite
This chapter assumes you know Dart null safety, async and await, basic Flutter widgets, and how to add packages in pubspec.yaml. Add path_provider, path, flutter_secure_storage and sqflite before you start.
Reading and writing files
A file is the simplest store for structured data. path_provider returns a directory the app may write to, and dart:io reads and writes the file.
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
Future<File> _notesFile() async {
final dir = await getApplicationDocumentsDirectory();
return File('${dir.path}/notes.json');
}
Future<void> saveNotes(List<Map<String, Object?>> notes) async {
final file = await _notesFile();
await file.writeAsString(jsonEncode(notes));
}
Future<List<Map<String, Object?>>> loadNotes() async {
final file = await _notesFile();
if (!await file.exists()) return [];
final decoded = jsonDecode(await file.readAsString()) as List<dynamic>;
return decoded.map((e) => e as Map<String, Object?>).toList();
}> Never hard-code a path such as /storage/emulated/0. Platforms restrict where apps may write, so always ask path_provider for a directory.
Keeping secrets in secure storage
A secret is a value that grants access, such as an auth token. Do not store secrets in shared_preferences or JSON files, because those values are readable on a rooted or compromised device. flutter_secure_storage keeps values in the Keychain on iOS and the Keystore on Android.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const _storage = FlutterSecureStorage();
Future<void> saveToken(String token) =>
_storage.write(key: 'auth_token', value: token);
Future<String?> readToken() => _storage.read(key: 'auth_token');
Future<void> clearToken() => _storage.delete(key: 'auth_token');Opening a SQLite database with sqflite
SQLite is an embedded database that stores tables in a single file. sqflite is a plugin that gives Dart access to SQLite on mobile devices. onCreate runs once, when the file is first created.
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
Future<Database> openNotesDatabase() async {
final path = join(await getDatabasesPath(), 'notes.db');
return openDatabase(
path,
version: 1,
onCreate: (db, version) async {
await db.execute(
'CREATE TABLE notes('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'body TEXT)',
);
},
);
}Insert, query, update and delete safely
Use the helper methods, and pass user values in whereArgs. Each ? placeholder is filled with a separate value, so SQLite treats the input as data, not as SQL.
Future<int> insertNote(Database db, String title, String? body) {
return db.insert('notes', {'title': title, 'body': body});
}
Future<List<Map<String, Object?>>> findNotes(Database db, String title) {
return db.query('notes', where: 'title = ?', whereArgs: [title]);
}
Future<int> updateNote(Database db, int id, String title) {
return db.update('notes', {'title': title}, where: 'id = ?', whereArgs: [id]);
}
Future<int> deleteNote(Database db, int id) {
return db.delete('notes', where: 'id = ?', whereArgs: [id]);
}Exercise
Why is where: 'id = ?', whereArgs: [id] safer than where: 'id = $id', and what can go wrong with the second form?
Show answer
The placeholder sends the value separately, so SQLite treats it as data. Interpolation places the text directly into the SQL, so input such as 1 OR 1=1 changes which rows match.