Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the color based on dark / light theme?

I want to set a dark and a light color scheme and use it as a background color of containers.

Here is my code:

Container(
  padding: const EdgeInsets.all(kDefaultPadding),
  //change required here:
  decoration: const BoxDecoration(color: kDarkColor),
  child: ... ,
)
like image 267
Jitan Gupta Avatar asked Oct 18 '25 16:10

Jitan Gupta


2 Answers

In your root file (main.dart) your entry point of the app is located. In general, you have a class MyApp which returns a MaterialApp widget. This out-of-the-box widget from the Flutter SDK lets you define your app´s theme. Here you can define the theme.

In your Container, you can assign the color directly via the color parameter. To refer to your theme data do this: Theme.of(context).backgroundColor for example.

like image 123
Jahn E. Avatar answered Oct 21 '25 05:10

Jahn E.


You can use platformBrightness from MediaQuery.

final isDarkTheme = MediaQuery.of(context).platformBrightness == Brightness.dark;

  Container(
    padding: const EdgeInsets.all(kDefaultPadding),
    //change required here
    decoration: const BoxDecoration(color: isDarkTheme? kDarkColor: kLightColor),
    child: Column(
    // ...
  ),

Also see how to implement dark mode in flutter

like image 25
Wilson Wilson Avatar answered Oct 21 '25 05:10

Wilson Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!