Flutter
Save theme
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.light
Default 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 value
Exercise Save and read the theme
Save the theme with setString('theme', 'dark'), read it with getString('theme') ?? 'light', and print it.
Show example 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')));
}
}
Test yourself
-
When should the saved theme be read?
- Only when the user taps a button
- On every build call
- When the app starts, inside main
- Never, the default is enough
Show answer
When the app starts, inside main — Reading the theme preference in main at startup means the user sees their theme immediately; no need to wait for a button tap.
-
Provide a default when reading theme
final theme = prefs.getString('theme') ____;
Show answer
final theme = prefs.getString('theme') ?? 'light';
-
Theme persistence parts
- 'theme'
- Key name
- setString
- Writes the theme
- getString
- Reads the theme
- themeMode
- MaterialApp property
Next lesson: Summary - shared_preferences