4

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: ... ,
)
Jahn E.
  • 1,228
  • 3
  • 6
  • 21
Jitan Gupta
  • 454
  • 6
  • 18

3 Answers3

4

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.

Jahn E.
  • 1,228
  • 3
  • 6
  • 21
1

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

Wilson Wilson
  • 3,296
  • 18
  • 50
1

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),
Jitan Gupta
  • 454
  • 6
  • 18