I have been asked some code to show how to display UI components from business logic without passing the BuildContext to the logic layer.

One way to do it, is through abstraction.

In this thread, I will show, step by step, how to display a SnackBar from the business logic.
🧵
The first thing we need, is to define a contract between our logic layer and our UI. One way to do it in Dart, is to create an abstract class.

Here, we just want to display a text through a SnackBar, so we will have this simple interface:
Now, we want to be able to call this SnackBarController from our Business Logic. One way to do it, is to pass it to the constructor of our business logic class.

By doing this, it's easily mockable and testable.
How to actually show the SnackBar and implement the contract can be done through a simple StatefulWidget.

Here I use Provider to provide our SnackBarController to its subtree, but you can use whatever DI system you want:
Now, we need to set up everything together. The ScaffoldMessenger is created by the MaterialApp, if we want to provide our SnackBarController to every pages of our app, we need to create it in the builder callback of the MaterialApp:
Then we need to provide a BusinessLogic instance to all the widgets of the page, so that they can use it.

We can do this like it with Provider, but again, you're not sticked to that library:
To finish, we just have to get the BusinessLogic instance from our widget when the user interacts with it, and that's it!
This was one way to do it, but there are other alternatives like using an Event Bus for example.
It may looks like a lot boilerplate comparing to simply pass the BuildContext, but by doing this, your code will be easier to test and maintain.
I think this thread can interest you @GowthamMG14 and @iamstanlee_
You can follow @lets4r.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: