A package that allows you to run functions that require BuildContext outside of Flutter widgets.

Installation

  • Drop ListenerThatRunsFunctionsWithBuildContext() somewhere in the application. It is best to place it in the root of the app.
    return Column(
          children: [
            child,
            const ListenerThatRunsFunctionsWithBuildContext(),
          ],
      ),

Usage

Wrap any functions that you want to run with a provider:

provideBuildContext(
    (context) => Navigator.pushNamed(context, '/somewhere'),
),

or

BuildContextProvider.provideBuildContext(
    (context) => Navigator.pushNamed(context, '/somewhere'),
),

Examples

class GoToProfilePage {
  static void call() {
    provideBuildContext(
      (context) => Navigator.pushNamed(context, '/profile'),
    );
  }
}

// This line can be used anywhere. As you can see you are not tied to build context anymore.
GoToProfilePage.call();

Tips

How does one use a value returned by the function? You must wrap your function and capture its result.

bool aValueToBeReturnedFromTheFunction = false;

bool functionThatReturnsValue(BuildContext context) {
  Navigator.of(context).pushNamed('/profile');
  return true;
}

void aFunctionThatCapturesReturnedValue(BuildContext context) {
  aValueToBeReturnedFromTheFunction = functionThatReturnsValue(context);
}

provideBuildContext(aFunctionThatCapturesReturnedValue);

expect(aValueToBeReturnedFromTheFunction, isTrue);

Design Principles

  1. No external libraries
  2. Do a single thing and nothing else