Created
January 5, 2023 07:30
-
-
Save kumar-aakash86/c79010cc6c1f27b0c1846191603e4dc9 to your computer and use it in GitHub Desktop.
Flutter - Theme Toggle from Drawer
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_bloc/flutter_bloc.dart'; | |
const Color darkBlue = Color.fromARGB(255, 18, 32, 47); | |
void main() { | |
runApp(App()); | |
} | |
class App extends StatelessWidget { | |
/// {@macro app} | |
const App({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return BlocProvider( | |
create: (_) => ThemeCubit(), | |
child: MyApp(), | |
); | |
} | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return BlocBuilder<ThemeCubit, ThemeData>( | |
builder: (_, theme) { | |
return MaterialApp( | |
theme: theme, | |
home: MyPage(), | |
); | |
}, | |
); | |
} | |
} | |
class MyPage extends StatefulWidget { | |
const MyPage({super.key}); | |
@override | |
State<MyPage> createState() => _MyPageState(); | |
} | |
class _MyPageState extends State<MyPage> { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: Text("Home")), | |
body: Container(color: const Color(0xFFFFE306)), | |
drawer: Drawer( | |
child: ListView( | |
// Important: Remove any padding from the ListView. | |
padding: EdgeInsets.zero, | |
children: <Widget>[ | |
const DrawerHeader( | |
decoration: BoxDecoration(color: Color(0x4D4971FF)), | |
//https://gist.github.com/lopspower/03fb1cc0ac9f32ef38f4 | |
child: Text( | |
'Header', | |
), | |
), | |
ListTile( | |
leading: const Icon(Icons.brush), | |
title: const Text( | |
'Dark Mode', | |
), | |
trailing: Switch( | |
value: context.read<ThemeCubit>().state.brightness == | |
Brightness.dark, | |
onChanged: (value) { | |
context.read<ThemeCubit>().toggleBrightness(); | |
}, | |
), | |
), | |
], | |
), | |
), | |
); | |
} | |
} | |
class ThemeCubit extends Cubit<ThemeData> { | |
/// {@macro brightness_cubit} | |
ThemeCubit() : super(_lightTheme); | |
static final _lightTheme = ThemeData( | |
floatingActionButtonTheme: const FloatingActionButtonThemeData( | |
foregroundColor: Colors.white, | |
), | |
brightness: Brightness.light, | |
); | |
static final _darkTheme = ThemeData( | |
floatingActionButtonTheme: const FloatingActionButtonThemeData( | |
foregroundColor: Colors.black, | |
), | |
brightness: Brightness.dark, | |
); | |
/// Toggles the current brightness between light and dark. | |
void toggleBrightness() { | |
emit(state.brightness == Brightness.dark ? _lightTheme : _darkTheme); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment