Looking for an answer from a senior architect in Flutter who knows the in and out of the SDK and the platform.
Objective is to get notified once a Stateful object comes to life or gets instantiated. The listener in this case is an isolated object.
At the moment I have solved using an EventBus
class, and the reason why I’m not satisfied is because I’m looking for something built-in or provided by the framework or the environment. (zero dependency, no 3rd party package either).
For example, in HTML and ReactJS we have window.addEventListener
, and dispatchEvent
. In Go language we have channels
. In iOS we have built-in Notification Center
(observer model)
I did try StreamController
but nay. Use case of it is different, it’s more of sending stream of data with error
and close
handlers. Not really a compatible use case.
Edit Lateral Thinking? maybe it’s not recommended but can we use keys to get hold of the instances, I can’t instantiate stateful widgets using the keys because they are instantiated automatically as user navigates the app.
Just think out loud here. Are they keys stored somewhere.
Foo
class Foo extends StatefulWidget {
const Foo({super.key});
@override
State<FooState> createState() => _FooState();
}
class _FooState extends State<Foo> {
@override
void initState() {
super.initState();
EventBus().dispatch("MOUNTED", this);
}
}
Bar
class Bar extends StatefulWidget {
const Bar({super.key});
@override
State<BarState> createState() => _BarState();
}
class _BarState extends State<Bar> {
@override
void initState() {
super.initState();
EventBus().dispatch("MOUNTED", this);
}
}
EventBus Objective is to get rid of this EventBus and use something provided by the Framework
class EventBus {
static final EventBus _instance = EventBus._internal();
factory EventBus() {
return _instance;
}
EventBus._internal();
final Map<String, List<void Function(dynamic sender)>> _listeners = {};
void subscribe(String event, void Function(dynamic sender) callback) {
if (_listeners[event] == null) {
_listeners[event] = [];
}
_listeners[event]!.add(callback);
}
void unsubscribe(String event, void Function(dynamic sender) callback) {
_listeners[event]?.remove(callback);
}
void dispatch(String event, dynamic sender) {
if (_listeners[event] != null) {
for (var callback in _listeners[event]!) {
callback(sender);
}
}
}
}
Isolated plain object – objective is to get to know once the widgets comes to life.
class Isolated {
void startup() {
EventBus().subscribe("MOUNTED", OnMount);
// lateral thinking, maybe get hold of Keys from the framework
}
void OnMount(dynamic sender) { // if either of foo and bar are instantiated.
// we can check sender here if it's `Foo` or `Bar`
}
}