Flutter
Persistent storage
Persist notes with shared_preferences.
Storing with shared_preferences
To make notes permanent you use the shared_preferences package. You first serialize the note list to a JSON string with jsonEncode, then store it with prefs.setString('notlar', s). When the app opens you read this string with prefs.getString('notlar'), decode it with jsonDecode, and convert it to a list with Note.fromJson.
final prefs = await SharedPreferences.getInstance();
final s = jsonEncode(notlar.map((n) => n.toJson()).toList());
await prefs.setString('notlar', s);
Reading and decoding
When reading the stored string you check the result of prefs.getString('notlar'). If the string exists you decode it into a List with jsonDecode and convert each element to a model with Note.fromJson. If it does not exist you start with an empty list.
final s = prefs.getString('notlar');
if (s == null) return [];
final liste = jsonDecode(s) as List;
return liste.map((e) => Note.fromJson(e as Map<String, dynamic>)).toList();
Exercise The notlariKaydet function
Write an async function named notlariKaydet. Get prefs with SharedPreferences.getInstance(), serialize the note list with jsonEncode (using notlar.map((n) => n.toJson()).toList()), then save it with prefs.setString('notlar', s). Print 'hazir' in main.
Show example solution
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class Note {
final String id;
final String baslik;
final String icerik;
Note(this.id, this.baslik, this.icerik);
Map<String, dynamic> toJson() => {'id': id, 'baslik': baslik, 'icerik': icerik};
}
Future<void> notlariKaydet(List<Note> notlar) async {
final prefs = await SharedPreferences.getInstance();
final s = jsonEncode(notlar.map((n) => n.toJson()).toList());
await prefs.setString('notlar', s);
}
void main() {
print('hazir');
}
Test yourself
-
What is done before saving the note list to shared_preferences?
- Serialize the list to a JSON string with jsonEncode
- Wrap the list in a Future
- Convert the list to a Widget
- Write the list to an sqflite table
Show answer
Serialize the list to a JSON string with jsonEncode — shared_preferences only stores primitive types; so you first serialize the note list with jsonEncode. Wrapping in a Future, converting to a Widget, and writing to sqflite are different operations and not needed here.
-
Store as a String
final s = jsonEncode(notlar.map((n) => n.toJson()).toList());
await prefs.____('notlar', s);
Show answer
final s = jsonEncode(notlar.map((n) => n.toJson()).toList());
await prefs.setString('notlar', s);
-
Persistent storage parts
- shared_preferences
- Persistent storage
- jsonEncode
- Serializing the list
- setString
- Writing a string
- jsonDecode
- Decoding the string
Next lesson: Summary - Note app