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?

2 Answers 2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.