5

I am saving my Text Styles in seperate text_styles.dart file. When i want to use theme colors just like Theme.of(context).primaryColor, I cant reach ThemeData object from text_styles.dart .I solved my problem with this kind of solution but this is not good solution.

TextStyle kWelcomePageHeaderTextStyle(BuildContext context) => TextStyle(
      fontFamily: "Courgette",
      fontSize: 30.0,
      color: Theme.of(context).primaryColor,
    );

So, i need to get ThemeData from static area for use my Text Styles like this.

const kWelcomePageHeaderTextStyle = TextStyle(
      fontFamily: "Courgette",
      fontSize: 30.0,
      color: [THEME_DATA_OBJECT_NEEDED].primaryColor,
    );

Can I get ThemeData object from text_styles.dart or is there any better solution?

Emirhan Soylu
  • 681
  • 6
  • 12

2 Answers2

4

I found better solution with Dependency Injection. I registered the dependency which is BuildContext in MaterialApp.

void main() {
  final GetIt sl = GetIt.instance;
  runApp(MaterialApp(
     theme: myLightTheme,
     darkTheme: myDarkTheme,
     builder: (BuildContext context, Widget widget) {
          if (!sl.isRegistered<BuildContext>()) {
              sl.registerSingleton<BuildContext>(context);
          }
          return HomePage();
     },
));

Then I can get Theme on the static area

const kWelcomePageHeaderTextStyle = TextStyle(
      fontFamily: "Courgette",
      fontSize: 30.0,
      color: Theme.of(sl.get<BuildContext>()).primaryColor,
    );
Emirhan Soylu
  • 681
  • 6
  • 12
0

Your app does not have a single, globally available theme. So you cannot get it.

Your app already has two themes out of the box (dark mode/light mode) and you can have many more. You can even have a different theme for a specific subtree in your build methods using the Theme widget. You can read more about it in the documentation.

Getting the Theme from the context is the preferred method.

nvoigt
  • 75,013
  • 26
  • 93
  • 142