build_context_provider 1.1.0 copy "build_context_provider: ^1.1.0" to clipboard
build_context_provider: ^1.1.0 copied to clipboard

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

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 Stack(
          children: [
            child,
            const ListenerThatRunsFunctionsWithBuildContext(),
          ],
      ),

Usage #

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

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

Examples #

class GoToProfilePage {
  static void call() {
    BuildContextProvider.call(
      (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);
}

BuildContextProvider()(aFunctionThatCapturesReturnedValue);

expect(aValueToBeReturnedFromTheFunction, isTrue);

Design Principles #

  1. No external libraries
  2. Do a single thing and nothing else
12
likes
160
points
633
downloads

Publisher

unverified uploader

Weekly Downloads

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

Repository (GitHub)
View/report issues

Documentation

API reference

License

BSD-3-Clause (license)

Dependencies

flutter

More

Packages that depend on build_context_provider