简体   繁体   中英

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.

我不确定是否有一种方法可以在像这样的小部件内使用primarySwatch但如果您正在寻找AppBar颜色,它实际上是primaryColor并且您可以使用它

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

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.

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(),
);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM