I have a container with background colour pink in light mode.. when changed to dark mode I want to change the colour to green. I have given the colours for both light mode and dark mode in the main page under themedata. There is no option for changing the container colour in themedata. What is the solution for this issue?
CodePudding user response:
You can use Theme.of(context).brightness
to check current theme mode.
Container(
color: Theme.of(context).brightness == Brightness.light
? Colors.pink
: Colors.green,
CodePudding user response:
The latest version of flutter supports a field in ColorsScheme known as "primaryContainer". You can set the value in both light and dark mode. On changing from light to dark and vice-versa, container color will be changed dynamically.
By default, surfaces such as Card Widget use surface color inside colorScheme, but container does not use any color. You have to set the color of container using Theme.of(context).colorScheme.(),
Set colorScheme in both light and dark theme as follows:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
useMaterial3: true,
colorScheme: const ColorScheme(
brightness: Brightness.light,
primary: Colors.orange,
onPrimary: Colors.white,
secondary: Colors.green,
onSecondary: Colors.white,
primaryContainer: Colors.orange,
error: Colors.black,
one rror: Colors.white,
background: Colors.blue,
onBackground: Colors.white,
surface: Colors.pink,
onSurface: Colors.white,
),
),
themeMode: ThemeMode.light,
darkTheme: ThemeData(
useMaterial3: true,
colorScheme: const ColorScheme(
brightness: Brightness.dark,
primary: Colors.red,
onPrimary: Colors.white,
secondary: Colors.green,
onSecondary: Colors.white,
primaryContainer: Colors.pink,
error: Colors.black,
one rror: Colors.white,
background: Colors.blue,
onBackground: Colors.white,
surface: Colors.pink,
onSurface: Colors.white,
),
),
themeMode: ThemeMode.light, // ThemeMode.dark
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
Then you can use color inside container such as
class Home extends StatelessWidget {
const Home({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
Theme.of(context).brightness == Brightness.dark
? "Dark Theme"
: "Light Theme",
),
),
body: Center(
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primaryContainer,
),
height: 300,
width: 300,
child: const Text('Hello'),
),
),
);
}
}