Flutter › App Theming & Dark Mode

How can you let a user manually select and persist their own preferred theme, such as light, dark, or system default, rather than only relying on the device's automatic system setting?

Intermediate

Answer

Letting a user manually choose their own preferred theme typically involves storing their selected preference using a persistent local storage mechanism such as SharedPreferences, then using a state management solution to hold the currently active theme mode in a way that the entire app can react to, rebuilding the MaterialApp's theme mode whenever that stored preference changes, ensuring the user's chosen theme is both immediately applied and correctly remembered the next time they open the app again.
final prefs = await SharedPreferences.getInstance();
await prefs.setString('theme_mode', 'dark');

// On app startup
final savedMode = prefs.getString('theme_mode') ?? 'system';
Real-world example A note taking app remembers a user's manually selected dark theme preference using SharedPreferences, correctly reopening in dark mode the next time the user launches the app, even if their device's own system wide setting happens to be light mode.

Common follow-ups: What state management approach works best for reactively updating the theme throughout the entire app?;Should theme preference be stored locally on the device or synced to a user's account across multiple devices?