Jitan Gupta
Jitan Gupta

Reputation: 484

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: ... ,
)

Upvotes: 4

Views: 4729

Answers (3)

Jahn E.
Jahn E.

Reputation: 1313

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.

Upvotes: 4

Jitan Gupta
Jitan Gupta

Reputation: 484

We can achieve this by reading the color from ThemeData.

Setting Themes

// light Theme
ThemeData lightThemeData(BuildContext context) {
  return ThemeData.light().copyWith(
    backgroundColor: Colors.grey.shade100,
  );
}

// dark Theme
ThemeData darkThemeData(BuildContext context) {
  return ThemeData.dark().copyWith(
    backgroundColor: Colors.grey.shade900,
  );
}

Configuring Theme in MaterialApp

      theme: lightThemeData(context),
      darkTheme: darkThemeData(context),

Finally using it

BoxDecoration(color: Theme.of(context).backgroundColor),

Upvotes: 1

Wilson Wilson
Wilson Wilson

Reputation: 3757

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

Upvotes: 1

Related Questions