'Flutter and realtime table in Supabase
I am using Provider to listen to realtime changes in a Supabase table.
Using MVVM the view is initialised by listening to the realtime table "poll_options"
poll_screen.dart
@override
void initState() {
asyncLoadData();
super.initState();
}
Future<void> asyncLoadData() async {
await Provider.of<PollScreenViewModel>(context, listen: false)
.subscribeToRealtimeVoteTable("poll_options");
}
The ViewModel has a function that subscribes to realtime changes:
poll_screen_viewmodel.dart
Future<void> subscribeToRealtimeVoteTable(String name) async {
var client = _supabaseService.getClient();
client.from(name).on(SupabaseEventTypes.all, (x) {
if (_pollPresentation != null) {
_pollPresentation = PollScreenPresentation(
id: x.newRecord['id'],
homeScreenImageUrl: x.newRecord['homeScreenImageUrl'],
);
}
notifyListeners();
}).subscribe();
}
My question is: How do I remove the subscription when using Provider and MVVM when the view is disposed?
@override
void dispose() {
// TODO: implement dispose
super.dispose();
}
If I would have all the code in the same class I would just call:
client.removeSubscription(client);
Solution 1:[1]
You could probably create a dispose() method in your poll_screen_viewmodel.dart and call it from your dispose() method within the widget?
Add this to your poll_screen_viewmodel.dart
void dispose() {
client.removeSubscription(client);
}
Add this on poll_screen.dart
@override
void dispose() {
Provider.of<PollScreenViewModel>(context, listen: false).dispose();
super.dispose();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dshukertjr |
