Save theme
- Flutter course
- Intermediate
- Lesson 39/99
- 4 min
Persist theme choice with shared_preferences.
Saving theme
To make the user's theme choice persistent, you use shared_preferences. You save the theme name as a String; when the app opens, you read it and pass it to MaterialApp's themeMode property. This way the user sees their chosen theme on every launch.
await prefs.setString('theme', 'dark');
final theme = prefs.getString('theme') ?? 'light';
// themeMode: theme == 'dark' ? ThemeMode.dark : ThemeMode.lightDefault theme with ??
On first launch, the 'theme' key doesn't exist yet; getString returns null. You provide a default value with the ?? operator. When the user selects a theme, you save it with setString; on subsequent launches, the saved value is used.
final saved = prefs.getString('theme');
final theme = saved ?? 'light';
print(theme); // 'light' or the saved valuePractice Save and read the theme
Save the theme with setString('theme', 'dark'), read it with getString('theme') ?? 'light', and print it.
Starter code
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
// setString ile 'theme' = 'dark' kaydet
// getString ile oku, yoksa 'light' ver
// print ile bastır
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body: Center(child: Text('tema')));
}
}Sample solution
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
await prefs.setString('theme', 'dark');
final theme = prefs.getString('theme') ?? 'light';
print(theme);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body: Center(child: Text('tema')));
}
}Expected output
dark
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When should the saved theme be read?
- Only when the user taps a button
- On every build call
- When the app starts, inside main Correct answer
- Never, the default is enough
Explanation: Reading the theme preference in main at startup means the user sees their theme immediately; no need to wait for a button tap.
2 Provide a default when reading theme
final theme = prefs.getString('theme') ____;
final theme = prefs.getString('theme') ?? 'light';
Explanation: If the key is absent, getString returns null; you use ?? to give 'light' as default.
3 Theme persistence parts
| Term | Meaning |
|---|---|
'theme' |
Key name |
setString |
Writes the theme |
getString |
Reads the theme |
themeMode |
MaterialApp property |