This is a simple Flutter app demonstrating the implementation of light and dark theme switching using Provider
for state management. The app displays a button inside a box, and when tapped, it toggles between light and dark themes.
- Switch between light and dark themes using a single button tap.
- Uses the
ChangeNotifierProvider
for managing state and theme updates. - Custom
MyBox
andMyButton
widgets for easy layout and design.
Light Mode | Dark Mode |
---|---|
- The main entry point of the app, which wraps the entire application inside a
ChangeNotifierProvider
to enable theme switching.
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => ThemeProvider(),
child: const MyApp(),
),
);
}
- A simple class that extends
ChangeNotifier
to handle theme toggling between light and dark modes.
class ThemeProvider with ChangeNotifier {
ThemeData _themeData = lightMode;
ThemeData get themeData => _themeData;
set themeData(ThemeData themeData) {
_themeData = themeData;
notifyListeners();
}
void toggleTheme() {
if (_themeData == lightMode) {
themeData = darkMode;
} else {
themeData = lightMode;
}
}
}
- Custom light and dark
ThemeData
defined to set colors for the primary, secondary, and surface.
ThemeData lightMode = ThemeData(
brightness: Brightness.light,
colorScheme: ColorScheme.light(
surface: Colors.grey.shade400,
primary: Colors.grey.shade300,
secondary: Colors.grey.shade200,
),
);
ThemeData darkMode = ThemeData(
brightness: Brightness.dark,
colorScheme: ColorScheme.dark(
surface: Colors.grey.shade900,
primary: Colors.grey.shade800,
secondary: Colors.grey.shade700,
),
);
- The main UI screen, which contains the
MyBox
widget with the theme switch button.
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.surface,
body: Center(
child: MyBox(
color: Theme.of(context).colorScheme.primary,
child: MyButton(
color: Theme.of(context).colorScheme.secondary,
onTap: () {
Provider.of<ThemeProvider>(context, listen: false).toggleTheme();
},
),
),
),
);
}
}
For questions or feedback, please contact @Bhavyansh03-tech on GitHub or connect with me on LinkedIn.