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
});
Share:
115
Lakshmanan Kumar
Author by

Lakshmanan Kumar

Updated on December 26, 2022

Comments

  • Lakshmanan Kumar
    Lakshmanan Kumar over 1 year

    I am working with flutter projects and I want to change the themecolor using an onpressed event

    I 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
      Randal Schwartz over 3 years
      You 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
    Lakshmanan Kumar over 3 years
    Thank you. But My Second Question is How to save this _ktheme variable on shared prefrences.
  • Ravi Singh Lodhi
    Ravi Singh Lodhi over 3 years
    Send me the question link & I will answer it there.
  • Lakshmanan Kumar
    Lakshmanan Kumar over 3 years