On this page15 sections
Lecture 008: Settings Screen: Theme Mode & Accent Colour
| Category | 4: The Final App |
| Lecture | 008 of 008 |
| Estimated video length | 16 min |
| Target | Flutter 3.44 · Dart 3.12 · provider 6.1 · shared_preferences 2.5 |
| Level | Beginner |
Time to finish My Notes: a proper Settings screen with a three-way Light / System / Dark picker and an accent colour picker. Both update the whole app instantly, and both are remembered. Everything from the course, in one app.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Lectures 001–007.
Connection With Previous Lectures
- The theme building from Lectures 002–003 moves into the provider (
themeFor), because the seed colour is now a setting. setThemeModefrom Lecture 007 gains a partner:setSeedColor.- The switch becomes a
SegmentedButton, which brings backThemeMode.system.
Learning Objectives
- Store two settings (mode and colour) in one provider
- Save a
Coloras anintwithtoARGB32() - Build both themes from the saved seed colour
- Use a
SegmentedButtonfor a three-way choice - Build a colour picker from a list of colours
1. The Final Structure
lib/
main.dart ← loads settings, NotesApp, HomeScreen
theme_provider.dart ← both settings, loading, saving, building themes
settings_screen.dart ← the mode picker and colour picker2. Saving a Colour
A Color is stored as one 32-bit number. toARGB32() gives that number, and Color(number)
turns it back into a colour:
await prefs.setInt('seed_color', Colors.indigo.toARGB32());
final color = Color(prefs.getInt('seed_color')!);Older tutorials use color.value, which is now deprecated:
info • 'value' is deprecated and shouldn't be used. Use component accessors like .r or .g, or toARGB32 for an explicit conversion.3. The Final ThemeProvider
lib/theme_provider.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ThemeProvider extends ChangeNotifier {
ThemeProvider(this._prefs, this._themeMode, this._seedColor);
static const _modeKey = 'theme_mode';
static const _colorKey = 'seed_color';
/// The accent colours the user can pick from.
static const List<Color> accents = [
Colors.teal,
Colors.indigo,
Colors.deepOrange,
Colors.pink,
Colors.green,
Colors.purple,
];
final SharedPreferences _prefs;
ThemeMode _themeMode;
Color _seedColor;
ThemeMode get themeMode => _themeMode;
Color get seedColor => _seedColor;
static Future<ThemeProvider> load() async {
final prefs = await SharedPreferences.getInstance();
final mode = ThemeMode.values.firstWhere(
(m) => m.name == prefs.getString(_modeKey),
orElse: () => ThemeMode.system,
);
final colorValue = prefs.getInt(_colorKey);
final color = colorValue == null ? accents.first : Color(colorValue);
return ThemeProvider(prefs, mode, color);
}
ThemeData themeFor(Brightness brightness) {
final colors = ColorScheme.fromSeed(seedColor: _seedColor, brightness: brightness);
return ThemeData(
colorScheme: colors,
appBarTheme: AppBarTheme(
backgroundColor: colors.primary,
foregroundColor: colors.onPrimary,
),
cardTheme: CardThemeData(
elevation: 0,
color: colors.secondaryContainer,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
),
);
}
Future<void> setThemeMode(ThemeMode mode) async {
if (mode == _themeMode) return;
_themeMode = mode;
notifyListeners();
await _prefs.setString(_modeKey, mode.name);
}
Future<void> setSeedColor(Color color) async {
if (color.toARGB32() == _seedColor.toARGB32()) return;
_seedColor = color;
notifyListeners();
await _prefs.setInt(_colorKey, color.toARGB32());
}
}Colours are compared with toARGB32(): Colors.teal is a MaterialColor (a colour with
shades), while Color(...) loaded from storage is a plain Color. Comparing their numbers is the
reliable way to ask "same colour?".
4. The Settings Screen
lib/settings_screen.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'theme_provider.dart';
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
final theme = context.watch<ThemeProvider>();
final text = Theme.of(context).textTheme;
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
Text('Appearance', style: text.titleMedium),
const SizedBox(height: 12),
SegmentedButton<ThemeMode>(
segments: const [
ButtonSegment(value: ThemeMode.light, icon: Icon(Icons.light_mode), label: Text('Light')),
ButtonSegment(value: ThemeMode.system, icon: Icon(Icons.phone_android), label: Text('System')),
ButtonSegment(value: ThemeMode.dark, icon: Icon(Icons.dark_mode), label: Text('Dark')),
],
selected: {theme.themeMode},
onSelectionChanged: (selection) =>
context.read<ThemeProvider>().setThemeMode(selection.first),
),
const SizedBox(height: 24),
Text('Accent colour', style: text.titleMedium),
const SizedBox(height: 12),
Wrap(
spacing: 12,
runSpacing: 12,
children: [
for (final color in ThemeProvider.accents)
_ColorDot(
color: color,
selected: color.toARGB32() == theme.seedColor.toARGB32(),
onTap: () => context.read<ThemeProvider>().setSeedColor(color),
),
],
),
],
),
);
}
}
class _ColorDot extends StatelessWidget {
const _ColorDot({required this.color, required this.selected, required this.onTap});
final Color color;
final bool selected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Semantics(
button: true,
selected: selected,
child: InkWell(
onTap: onTap,
customBorder: const CircleBorder(),
child: CircleAvatar(
radius: 22,
backgroundColor: color,
child: selected ? const Icon(Icons.check, color: Colors.white) : null,
),
),
);
}
}SegmentedButtontakes a set of selected values ({theme.themeMode}), because it can also allow several selections. Here exactly one is selected, soselection.firstis the new mode.- Each colour is a
_ColorDot: a tappable circle with a check mark when selected.Semanticstells screen readers it's a button and whether it's selected.
Code Examples
Example 1: The Finished App
lib/main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'settings_screen.dart';
import 'theme_provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final themeProvider = await ThemeProvider.load();
runApp(
ChangeNotifierProvider.value(
value: themeProvider,
child: const NotesApp(),
),
);
}
class NotesApp extends StatelessWidget {
const NotesApp({super.key});
@override
Widget build(BuildContext context) {
final theme = context.watch<ThemeProvider>();
return MaterialApp(
title: 'My Notes',
debugShowCheckedModeBanner: false,
theme: theme.themeFor(Brightness.light),
darkTheme: theme.themeFor(Brightness.dark),
themeMode: theme.themeMode,
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
const notes = ['Buy milk and bread', 'Call the plumber', 'Revise Lecture 008'];
return Scaffold(
appBar: AppBar(
title: const Text('My Notes'),
actions: [
IconButton(
tooltip: 'Settings',
icon: const Icon(Icons.settings),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const SettingsScreen()),
),
),
],
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
for (final note in notes)
Card(
child: ListTile(title: Text(note)),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: const Icon(Icons.add),
),
);
}
}Try it: open ⚙ Settings, choose Dark, tap the orange dot. The settings screen, the app bar, the cards and the button all change at once. Go back, then fully restart the app: it opens dark and orange.
Tested: choosing Dark and the third colour set MaterialApp.themeMode to dark, built the dark
theme from Colors.deepOrange, showed one check mark, saved theme_mode = 'dark' and
seed_color = Colors.deepOrange.toARGB32(), and a fresh load() restored both.
Common Beginner Mistakes
1. Comparing colours with ==: Colors.teal == Color(Colors.teal.toARGB32()) can be
false, because one is a MaterialColor and the other a plain Color. Compare
toARGB32() values, as setSeedColor and _ColorDot do.
2. Deprecated colour APIs: color.value and color.withOpacity(0.5) still appear in many
tutorials:
info • 'withOpacity' is deprecated and shouldn't be used. Use .withValues() to avoid precision loss.Use toARGB32() and color.withValues(alpha: 0.5).
3. Building ThemeData in two places: once the seed colour is a setting, a separate
buildTheme() with a fixed Colors.teal would ignore the user's choice. Build themes in one
place, from the provider's state.
4. Forgetting that SegmentedButton.selected is a set: pass {theme.themeMode}, not
theme.themeMode.
Best Practices
- One provider owns all appearance settings: loading, saving and building themes.
- Offer a fixed palette of tested accent colours rather than any colour, so contrast stays good.
- Give custom tappable widgets
Semanticsso they work with screen readers. - Keep screens thin: they show state (
watch) and call methods (read), nothing more.
Mini Challenge
Add a Reset to defaults button to the Settings screen. Give ThemeProvider a reset() method
that sets the mode to ThemeMode.system and the colour to accents.first, notifies, and removes
both keys from SharedPreferences.
Practice Questions
- How is a
Colorsaved in SharedPreferences? - Why does
themeForlive in the provider now? - What does
SegmentedButton'sselectedexpect? - Why compare colours with
toARGB32()instead of==? - Trace what happens, step by step, when the user taps the pink dot.
Practice Answers
- As an
int:setInt(key, color.toARGB32()), read back withColor(prefs.getInt(key)!). - The seed colour is a setting stored in the provider, so the themes must be built from it.
- A
Setof selected values, e.g.{ThemeMode.dark}. - A
MaterialColorand a plainColorwith the same value may not be==; their numbers always match. onTap→context.read<ThemeProvider>().setSeedColor(Colors.pink)→_seedColorchanges →notifyListeners()→NotesApp(watching) rebuilds →themeForbuilds pink themes → the whole app turns pink → the colour is saved withsetInt.
Key Takeaways
- One provider holds both settings; screens just watch and call methods.
- Save colours with
toARGB32(), compare them by that number, and avoid deprecated.value. - Build themes from the provider's state, in one place.
SegmentedButtongives a clean Light / System / Dark choice.- You've built a complete, persistent theming system: the same pattern works for language, font size or any other app setting.
Full Code (Copy-Paste Reference)
The complete, finished app: every file, as it stands at the end of the course.
lib/theme_provider.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ThemeProvider extends ChangeNotifier {
ThemeProvider(this._prefs, this._themeMode, this._seedColor);
static const _modeKey = 'theme_mode';
static const _colorKey = 'seed_color';
/// The accent colours the user can pick from.
static const List<Color> accents = [
Colors.teal,
Colors.indigo,
Colors.deepOrange,
Colors.pink,
Colors.green,
Colors.purple,
];
final SharedPreferences _prefs;
ThemeMode _themeMode;
Color _seedColor;
ThemeMode get themeMode => _themeMode;
Color get seedColor => _seedColor;
/// Reads both saved settings once, before the app starts.
static Future<ThemeProvider> load() async {
final prefs = await SharedPreferences.getInstance();
final mode = ThemeMode.values.firstWhere(
(m) => m.name == prefs.getString(_modeKey),
orElse: () => ThemeMode.system,
);
final colorValue = prefs.getInt(_colorKey);
final color = colorValue == null ? accents.first : Color(colorValue);
return ThemeProvider(prefs, mode, color);
}
/// Builds a full theme (light or dark) from the current seed colour.
ThemeData themeFor(Brightness brightness) {
final colors = ColorScheme.fromSeed(seedColor: _seedColor, brightness: brightness);
return ThemeData(
colorScheme: colors,
appBarTheme: AppBarTheme(
backgroundColor: colors.primary,
foregroundColor: colors.onPrimary,
),
cardTheme: CardThemeData(
elevation: 0,
color: colors.secondaryContainer,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
),
);
}
Future<void> setThemeMode(ThemeMode mode) async {
if (mode == _themeMode) return;
_themeMode = mode;
notifyListeners();
await _prefs.setString(_modeKey, mode.name);
}
Future<void> setSeedColor(Color color) async {
// toARGB32() comparison: a MaterialColor and a plain Color with the same
// value are not always == to each other, but their raw numbers always match.
if (color.toARGB32() == _seedColor.toARGB32()) return;
_seedColor = color;
notifyListeners();
await _prefs.setInt(_colorKey, color.toARGB32());
}
}lib/settings_screen.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'theme_provider.dart';
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
final theme = context.watch<ThemeProvider>();
final text = Theme.of(context).textTheme;
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
Text('Appearance', style: text.titleMedium),
const SizedBox(height: 12),
// SegmentedButton.selected takes a SET of values, even for a single choice.
SegmentedButton<ThemeMode>(
segments: const [
ButtonSegment(value: ThemeMode.light, icon: Icon(Icons.light_mode), label: Text('Light')),
ButtonSegment(value: ThemeMode.system, icon: Icon(Icons.phone_android), label: Text('System')),
ButtonSegment(value: ThemeMode.dark, icon: Icon(Icons.dark_mode), label: Text('Dark')),
],
selected: {theme.themeMode},
onSelectionChanged: (selection) =>
context.read<ThemeProvider>().setThemeMode(selection.first),
),
const SizedBox(height: 24),
Text('Accent colour', style: text.titleMedium),
const SizedBox(height: 12),
Wrap(
spacing: 12,
runSpacing: 12,
children: [
for (final color in ThemeProvider.accents)
_ColorDot(
color: color,
selected: color.toARGB32() == theme.seedColor.toARGB32(),
onTap: () => context.read<ThemeProvider>().setSeedColor(color),
),
],
),
],
),
);
}
}
class _ColorDot extends StatelessWidget {
const _ColorDot({required this.color, required this.selected, required this.onTap});
final Color color;
final bool selected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Semantics(
button: true,
selected: selected,
child: InkWell(
onTap: onTap,
customBorder: const CircleBorder(),
child: CircleAvatar(
radius: 22,
backgroundColor: color,
// Check mark shows which accent is currently selected.
child: selected ? const Icon(Icons.check, color: Colors.white) : null,
),
),
);
}
}lib/main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'settings_screen.dart';
import 'theme_provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final themeProvider = await ThemeProvider.load();
runApp(
ChangeNotifierProvider.value(
value: themeProvider,
child: const NotesApp(),
),
);
}
class NotesApp extends StatelessWidget {
const NotesApp({super.key});
@override
Widget build(BuildContext context) {
final theme = context.watch<ThemeProvider>();
return MaterialApp(
title: 'My Notes',
debugShowCheckedModeBanner: false,
theme: theme.themeFor(Brightness.light),
darkTheme: theme.themeFor(Brightness.dark),
themeMode: theme.themeMode,
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
const notes = ['Buy milk and bread', 'Call the plumber', 'Revise Lecture 008'];
return Scaffold(
appBar: AppBar(
title: const Text('My Notes'),
actions: [
IconButton(
tooltip: 'Settings',
icon: const Icon(Icons.settings),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const SettingsScreen()),
),
),
],
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
for (final note in notes)
Card(
child: ListTile(title: Text(note)),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: const Icon(Icons.add),
),
);
}
}