Search code examples
androidiosflutterflutter-getx

Failed to interpolate TextStyles with different inherit values


I have two functions of theme, darkThemeData, and lightThemeData. However, when the App is run, the theme works fine with Poppins as the default font but when I click the button to switch to Dark mode I get this error and the fontFamily is lost. I tried different solutions but I am stuck.

  Widget build(BuildContext context) {
    final ThemeData lightThemeData = ThemeData(
      
      textTheme: GoogleFonts.poppinsTextTheme(
        Theme.of(context).textTheme.copyWith(
              bodyMedium: GoogleFonts.poppins(),
              displaySmall: GoogleFonts.poppins(),
            ),
      ),
    );

    final ThemeData darkThemeData = ThemeData(
      
      textTheme: GoogleFonts.poppinsTextTheme(
        Theme.of(context).textTheme.copyWith(
             bodyMedium: GoogleFonts.poppins(),
              displaySmall: GoogleFonts.poppins(),
            ),
      ),
    );

    return GetMaterialApp(

      debugShowCheckedModeBanner: false,
      theme: darkmode == false ? darkThemeData : lightThemeData,
      home: navbar(),
    
    );
  }


Solution

  • Try this implementation

    import 'package:flutter/material.dart';
    import 'package:google_fonts/google_fonts.dart';
    
    bool darkMode = false;
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        final ThemeData lightThemeData = ThemeData(
          primarySwatch: Colors.blue,
          textTheme: GoogleFonts.poppinsTextTheme(
            Theme.of(context).textTheme,
          ),
        );
    
        final ThemeData darkThemeData = ThemeData(
          primarySwatch: Colors.blue,
          brightness: Brightness.dark,
          textTheme: GoogleFonts.poppinsTextTheme(
            Theme.of(context).textTheme,
          ),
        );
    
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: darkMode ? darkThemeData : lightThemeData,
          home: navbar(),
        );
      }
    }
    

    Don't need to explicitly set the font for each text style since we use the GoogleFonts.poppinsTextTheme() font "Poppins" for the entire text theme.