build_context_provider 1.1.0 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 #
- No external libraries
- Do a single thing and nothing else