Sub topic 1
Where can a Flutter app keep data?
Prerequisites
This chapter assumes you know Dart classes and null safety, Future with async and await, basic widgets, and how to add packages in pubspec.yaml.
Storage options at a glance
A Flutter app can keep data on the device in four main ways. Key-value preferences hold small settings. Files hold documents or larger blobs. Secure storage holds secrets such as tokens. A SQLite database holds structured records that you can query.
Saving settings with shared_preferences
shared_preferences is a package that stores small key-value pairs on the device. Use it for flags such as a dark mode setting. Do not use it for large or sensitive data.
import 'package:shared_preferences/shared_preferences.dart';
Future<void> saveDarkMode(bool value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('dark_mode', value);
}
Future<bool> loadDarkMode() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool('dark_mode') ?? false;
}Turning models into maps and JSON
Storage APIs accept primitive values, not Dart objects. A model class therefore needs toMap and fromMap methods that convert to and from Map<String, Object?>. jsonEncode then turns the map into JSON text.
import 'dart:convert';
class Note {
const Note({this.id, required this.title, this.body});
final int? id;
final String title;
final String? body;
Map<String, Object?> toMap() => {
'id': id,
'title': title,
'body': body,
};
factory Note.fromMap(Map<String, Object?> map) => Note(
id: map['id'] as int?,
title: map['title'] as String,
body: map['body'] as String?,
);
}
String encodeNote(Note note) => jsonEncode(note.toMap());Finding the right directory with path_provider
path_provider is a package that returns platform-specific folders. getApplicationDocumentsDirectory returns a folder for user data that the platform normally backs up. getTemporaryDirectory returns a cache folder that the operating system may clear at any time.
import 'package:path_provider/path_provider.dart';
Future<String> documentsPath() async {
final dir = await getApplicationDocumentsDirectory();
return dir.path;
}Exercise
Where should an app keep a downloaded image cache that it can rebuild if it is lost?
Show answer
In the temporary directory from getTemporaryDirectory. The operating system may clear it, and the app can download the images again.