Accessing context / creating snackbars #191
-
I'm testing out ReArch to see if it can be used on a real app and have stumbled early in the process. Most apps need to be able to raise SnackBars and perform other operations using the build context in response to async events (such as an incoming websocket message or device hardware status change). Since Capsules don't have access to the context, how am I supposed to be able to react to an async event? In Bloc I would simply have a listener that sees when my Cubit state had changed and that listener provided me with the build context required to take actions like showing a snackbox. I see there are "listeners" in ReArch too but I can't work out how to use them in any way that provides the build context. Alternatively there are WidgetSideEffects which sound like they are part of the solution but I can't work out how to trigger one in response to something happening in the Capsule graph. Overall, despite reading much of this discussion forum, the MSc paper and the documentation website, I have found it hard to understand how the Capsule graph relates to the Flutter Widget tree so perhaps that is the underlying reason that I can't see any way forward at the moment. Please can someone point me in the correct direction? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Hi! 👋 Capsules form a graph of business logic and app/global-level state, so naturally they don't have a BuildContext or some other means to access the UI directly. UI code is separated cleanly via You have a few options here, in order of preference/testability:
onPressed: () async {
await myAsyncFunction();
if (!context.isMounted) return; // maybe it's context.mounted, can't remember
ScaffoldMessenger.of(context).showSnackBar(...);
},
@rearchWidget
Widget snackbarListener(BuildContext context, WidgetHandle use, Widget child) {
final data = use(myCapsule);
final previousData = use.previous(data);
if (data != previousData) {
WidgetsBinding.instance!.addPostFrameCallback((_) {
ScaffoldMessenger.of(context).showSnackBar(...);
});
}
return child;
}
// elsewhere:
const Scaffold(
body: SnackbarListener(
child: MyOtherChild(),
),
);
Scaffold(
snackbar: SnackBar(...) // or null to hide, perhaps
); No clue why Flutter didn't do that (maybe ease of use in simple situations), but it's a design anomaly compared to the rest of the framework.
Typically this is done via: |
Beta Was this translation helpful? Give feedback.
Hi! 👋
Capsules form a graph of business logic and app/global-level state, so naturally they don't have a BuildContext or some other means to access the UI directly. UI code is separated cleanly via
flutter_rearch
withRearchConsumer
s. Thus, you have to go to UI code to change the UI.You have a few options here, in order of preference/testability:
SnackBar
that you animate yourself, but often you use a more custom widget).use.mutation
anyways, read on). In this case, you can do: