Flutter Theme Changing dark to light using onpress event
115
Your theme objects _lightTheme
& _darkTheme
are the same objects with different names.
They both have brightness
set to Brightness.light
& primaryColor
as Colors.white
.
ThemeData _lightTheme = ThemeData(
brightness: Brightness.light, // <----
primaryColor: Colors.white, // <----
);
ThemeData _darkTheme = ThemeData(
brightness: Brightness.light, // <--- Dark mode having light brightness
primaryColor: Colors.white, // <---- Dark mode having white color
);
Change these to the following:
ThemeData _lightTheme = ThemeData(
brightness: Brightness.light, // light mode
primaryColor: Colors.white,
);
ThemeData _darkTheme = ThemeData(
brightness: Brightness.dark, // dark mode
primaryColor: Colors.black,
);
Also, your onPressed
code looks wrong.
setState(() {
_ktheme = !_ktheme; // Notice: I renamed ktheme to _ktheme
});
Author by
Lakshmanan Kumar
Updated on December 26, 2022Comments
-
Lakshmanan Kumar over 1 year
I am working with flutter projects and I want to change the themecolor using an
onpressed
eventI tried some code but not working.
main.dart file
import 'package:flutter/material.dart'; import 'Screens/HomePage.dart'; void main()=> runApp(MyApp()); ThemeData _lightTheme = ThemeData( brightness: Brightness.light, primaryColor: Colors.white, ); ThemeData _darkTheme = ThemeData( brightness: Brightness.light, primaryColor: Colors.white, ); bool _ktheme = true; class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Wallbay', theme: _ktheme ? _lightTheme : _darkTheme, home: MyHomePage('Alpha Papers'), ); } }
HomePage.dart file
........ IconButton( icon: Icon(Icons.brightness_medium_outlined), onPressed: () { setState(() { _ktheme = !ktheme; }); }, ) ......
-
Randal Schwartz over 3 yearsYou can't just say "doesn't work". What does it do, and how is that different from your expectations, and what have yoouo tried when you're fixing it?
-
-
Lakshmanan Kumar over 3 yearsThank you. But My Second Question is How to save this _ktheme variable on shared prefrences.
-
Ravi Singh Lodhi over 3 yearsSend me the question link & I will answer it there.
-
Lakshmanan Kumar over 3 years