Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter: How to get a value inside ThemeData?

I’m trying to style my app globally and I have some questions about hot the properly retrieve the value like this!

This code it’s not working because there is no context at this point, but is there some way to get this value?

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

ThemeData lightTheme = ThemeData(
  useMaterial3: true,
  
  // Text Style
  textTheme: TextTheme(
    titleMedium: GoogleFonts.nunito(fontWeight: FontWeight.bold, letterSpacing: -1, fontSize: 16),
  ),

  // AppBar
  appBarTheme: AppBarTheme(
    titleTextStyle: Theme.of(context).textTheme.titleMedium,
  ),
);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Instead of globally declaring theme data, use a class with static method returning themeData with context as parameter:

@override
Widget build(BuildContext context) {
  return MaterialApp(
    theme: ThemeClass.getThemeData(context),
    home: const HomePage(),
  );
}

class ThemeClass {
  static getThemeData(BuildContext context) {
    final lightTheme = ThemeData(
      useMaterial3: true,

      // Text Style
      textTheme: TextTheme(
        titleMedium: GoogleFonts.nunito(
            fontWeight: FontWeight.bold, letterSpacing: -1, fontSize: 16),
      ),

      // AppBar
      appBarTheme: AppBarTheme(
        titleTextStyle: Theme.of(context).textTheme.titleMedium,
      ),
    );

    return lightTheme;
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading