Last active
May 23, 2024 13:26
-
-
Save sgruhier/a2e86979eeb6a90482578b581bab21d1 to your computer and use it in GitHub Desktop.
Theme with riverpod - StateNotifier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_riverpod/flutter_riverpod.dart'; | |
class ThemeNotifier extends StateNotifier<ThemeData> { | |
ThemeNotifier() : super(ThemeData.light()); | |
bool isLight() { | |
return state == ThemeData.light(); | |
} | |
void toggleTheme() { | |
state = isLight() ? ThemeData.dark() : ThemeData.light(); | |
} | |
} | |
final themeDataProvider = StateNotifierProvider<ThemeNotifier, ThemeData>((ref) { | |
return ThemeNotifier(); | |
}); | |
void main() { | |
runApp(ProviderScope(child: MyApp())); | |
} | |
class MyApp extends ConsumerWidget { | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
final themeData = ref.watch(themeDataProvider); | |
return MaterialApp( | |
title: 'Flutter Theme Switcher', | |
theme: themeData, | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends ConsumerWidget { | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
final theme = ref.watch(themeDataProvider); | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Flutter Theme Switcher'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Text( | |
'Current Theme: ${theme == ThemeData.light() ? "Light" : "Dark"}', | |
), | |
Switch( | |
value: theme == ThemeData.dark(), | |
onChanged: (bool value) { | |
ref.read(themeDataProvider.notifier).toggleTheme(); | |
}, | |
), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment