I am designing a container in flutter, based on the theme, it can be dark or light, I want to change the background color of container.
I did some researched and didn't found any ways, so my question is
Is it even possible to do? If yes, then how?
I am new to Flutter, so if it's basic question, please don't mind.
Here is my code
Container(
padding: const EdgeInsets.all(kDefaultPadding),
//change required here
decoration: const BoxDecoration(color: kDarkColor),
child: Column(
// ...
))
CodePudding user response:
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.
CodePudding user response:
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
CodePudding user response:
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),