'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.



Solution 1:[1]

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;

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CopsOnRoad
Solution 2 Yashu Agrawal