Home > Software engineering >  How Can I get rid of the context dependency for using Theme on the Flutter?
How Can I get rid of the context dependency for using Theme on the Flutter?

Time:07-22

in short, I have a custom Theme file and I'm using that theme on the GetMaterialApp widget. But when I use the that themes(for instance textStyle or Icon color), I always need to context.

I mean, there is my theme class at the below .

import 'package:flutter/material.dart';
import 'package:professional_app/Utilities/colors.dart';

class CustomLightTheme {
  final ThemeData theme = ThemeData(
    elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
      textStyle: const TextStyle(
        fontWeight: FontWeight.bold,
      ),
      primary: Colors.blue,
      onPrimary: Colors.white,
    )),
    textTheme: TextTheme(
        bodyText2: TextStyle(
          fontFamily: "CormorantSC",
          fontSize: 16,
          color: colorOfPinkSwan.withOpacity(0.5),
          overflow: TextOverflow.ellipsis,
        ),
        bodyText1: const TextStyle(
          fontSize: 24,
          color: Colors.white,
          overflow: TextOverflow.ellipsis,
        )),
    buttonTheme: ButtonThemeData(
      buttonColor: colorOfDullLavender,
    ),
    appBarTheme: AppBarTheme(
      backgroundColor: colorOfPerfume,
      foregroundColor: colorOfCinder,
    ),
  );
}

and I'm using that on the GetMaterialApp Widget:

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    debugPrint("MyApp class has worked.");
    return GetMaterialApp(
      transitionDuration: durationOfLow,
      defaultTransition: Transition.fadeIn,
      getPages: getPages,
      theme: CustomLightTheme().theme,
      initialRoute: pathOfHomePage,
      unknownRoute:
          GetPage(name: pathOfErrorPage, page: () => const ErrorPage()),
      debugShowCheckedModeBanner: false,
    );
  }
}

So, When I wanna use the that theme features, I always need to context. For example:

_text({required BuildContext context, required String text}) {
  return Text(
    style: Theme.of(context).textTheme.bodyText1,
    text,
    textAlign: TextAlign.justify,
    maxLines: 2,
    overflow: TextOverflow.ellipsis,
  );
}

That is a method that return my text widget but I don't wanna send context like parameter to that text method.

is there any way to get rid of context dependency? Or Can I use GetX to that problem?

Many Thanks...

CodePudding user response:

Step 1:

create a variable on top of your main.dart file like below:

final navigatorKey = GlobalKey<NavigatorState>();

Step 2:

add navigatorKey to your GetMaterialApp like below:

 return GetMaterialApp(
  navigatorKey: navigatorKey,
  ...
);

Now

use this navigatorKey anywhere to access context using the following line:

navigatorKey.currentState!.overlay!.context
  • Related