Làm sao để tạo chức năng chuyển dark/light theme trong Flutter?
Làm sao để tạo chức năng chuyển dark/light theme trong Flutter?
themeModeclass App extends ConsumerWidget {
const App({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final mode = ref.watch(themeModeProvider); // ThemeMode.system / light / dark
return MaterialApp(
theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo)),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo, brightness: Brightness.dark),
),
themeMode: mode,
home: const HomePage(),
);
}
}
ThemeMode.system tự theo cài đặt sáng/tối của điện thoại.
Ví dụ với Riverpod + shared_preferences (với Provider, Bloc làm tương tự):
final themeModeProvider = NotifierProvider<ThemeModeNotifier, ThemeMode>(ThemeModeNotifier.new);
class ThemeModeNotifier extends Notifier<ThemeMode> {
static const _key = 'theme_mode';
@override
ThemeMode build() {
final saved = ref.read(prefsProvider).getString(_key); // prefs đã khởi tạo trong main
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.