How to automatically update UI with the new tasks?
For example, while I’m on the tasks page, I load them once. In the meantime, let’s say new task are created and stored from my web application to mysql db. I would still see only previously loaded tasks without any idea that the new record is created in the database.
I’m using ListView.builder to display the data, while calling the API on initState(). Also, it might be worth noting, I’m using Laravel with MySql for my backend.
What is the best way to update UI with new data whenever there is a new record in the mysql database?
2
Answers
This might need a little bit of a more complex setup, as you are trying to build an app that is sort real time.
You could go explore Polling -> where you make call to the api endpoint after an interval of say 30 seconds
Or better yet you could explore websockets.
I would argue websockets is the better alternative.
Polling doesnt require any change on your backend, just a timer countdown of sorts -> Have a look at this : https://api.flutter.dev/flutter/dart-async/Timer/Timer.periodic.html.
For websockets, Pusher ,an abstraction of the low level websocket implementation, is quite common on Laravel and quite straight forward to setup. You could start with with the with this closed source option https://pusher.com. Its easier very well documented and has pretty well maintained Flutter package.
On your flutter app, I would advice a better form of state management like Bloc or RiverPod coupled with the Pusher flutter package (https://github.com/pusher/pusher-channels-flutter), to subscribe and listen to channels and events. The state management bit is just to enable you to work with streams and to have cleaner and maintable code.
Depending on how you architecture of streams you might also need to explore the Streambuilder widget