I have a problem with theming a flutter app. I cannot get the primary color from of the theme. Here is the example code
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: const ColorScheme.light(
primary: Colors.blue,
secondary: Colors.amber,
),
useMaterial3: true,
),
darkTheme: ThemeData(
colorScheme: const ColorScheme.dark(
primary: Colors.grey,
secondary: Colors.white,
),
useMaterial3: true,
),
themeMode: ThemeMode.system,
home: Scaffold(
body: Center(
child: SizedBox(
height: 200,
width: 200,
child: Container(
color: Theme.of(context).colorScheme.primary,
),
),
),
),
);
}
}
I want the container to have the primary color of the theme which is blue in light mode and grey in dark mode. But It always shows purple color in both light and dark mode
Light Mode
Dark Mode
I have tried different solution many times. But result is same. I am new to flutter. I hope a kind reply.
Thank you.
2
Answers
pasanmaduranga, Well done on starting!
Try to first centralize your themeData in a seperate file and just calling that. You can use a class with static variables.
Centralizing texts (strings), colors, and theme data makes it easier to edit in the long run of the project or program.
theme.dart file:
Usage:
Back to your question:
You were close by using the Theme.of(context), as Theme.of(context) allows you to access the currently active theme on the app by the Buildcontext, context.
You just need to use:
It will retrieve the current primary color available in the themeData based on the context.
Meaning, if its lightmode, it will return the light mode’s primary color and vice versa.
So in your case:
Happy coding pasanmaduranga!!!
modify to this for most simple
the context is not yet aware of the changes in theme