How to pass data from Singleton to Stateful Widget class?

Issue

I have a class Communicator which where I’ve declared a few functions. Executing those function takes some time and an update of progress is required till all the functions get executed.

Now, I am using the functions of class Communicator in my stageful widget class HomeScreen. I want to pass the progress data from Communicator to HomeScreen and update the widget regularly upon receiving the progress data. How can this be achieved?

Solution

Communicator.addSomeListener(_handleSomeEvent); in init, and Communicator.removeSomeListener(_handleSomeEvent) in dispose.

void _handleSomeEvent(SomePayload data) => setState((){});

Your singleton can keep a list of these callbacks, and call them.

Answered By – shawnblais

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *