Mahdi-Malv
Mahdi-Malv

Reputation: 19200

How to get theme color inside the widget in Flutter

I have this:

Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AnApp',
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
      ),
      home: MainWidget()
    );
  }
}

So I have set primarySwatch color to blueGrey. How can I access this color inside the MainWidget class?

I want to set a background the same as the AppBar color.

Upvotes: 56

Views: 55081

Answers (4)

Ec7ipse
Ec7ipse

Reputation: 77

Just make sure. If you use CupertinoApp i think it would be more appropriate to use CupertinoTheme.of(context)

Upvotes: 0

vijay rathore
vijay rathore

Reputation: 11

Please create the AppTheme class and setup dark and light theme

 Widget build(BuildContext context) {
return MaterialApp(
  debugShowCheckedModeBanner: false,
   theme: AppTheme.lightTheme,
   darkTheme: AppTheme.darkTheme,
   themeMode: theme.isDarkMode ? ThemeMode.dark : ThemeMode.light,

  home: SplashScreen(),
);

}

Upvotes: 0

Yashu Agrawal
Yashu Agrawal

Reputation: 79

You can use:

color: Theme.of(context).primarySwatch;

OR

you can change the primaryswatch color in main theme class instead of changing in your class by -

Clicking on ctrl + primarySwatch, You will be Headed to theme_data page and there you can change your theme color according to your convience.

Upvotes: -1

CopsOnRoad
CopsOnRoad

Reputation: 267434

I'm not sure if there exist a way to use primarySwatch inside widget like that but if you are looking for AppBar color, it is actually the primaryColor and you can get it using

Color color = Theme.of(context).primaryColor;

Upvotes: 113

Related Questions