FlutterPaginator
FlutterPaginator copied to clipboard
Cancel future on dispose()
The load data future should be canceled on dispose of the StatefulWidget. This can be achieved using CancelableOperation
which is included in the default package package:async/async.dart
.
This will prevent the following error:
Unhandled Exception: setState() called after dispose()
Did you solved it? If yes, how?
Hi @TomasWeg ,
we decided to handle pagination differently, because of that I did not solve it.
I think the best solution would be to use a CancelableOperation
instead of Future
in this type definition https://github.com/UdaraWanasinghe/FlutterPaginator/blob/master/lib/type_definitions.dart#L3 and cancel the operation in the dispose
callback.
@philipgiuliani Can you provide a code sample, please? I think I did it, but I want to make sure. Thank you
As another precaution, in case the futures are not cancelled, my PR (#7) also fixes this issue.
I think this is more elegant than cancelling the requests, because if the widget is mounted again, the request can still be useful.
You can "convert" a Future to Stream to Flutter listen Future as a Stream. Example:
StreamSubscription<List<Data>>? subscription;
List<Data> _data = [];
void _getDataFutureAsStream() {
subscription = ApiFuture().asStream().listen((value) {
setState(() => _data.addAll(value));
});
}
@override
initState(){
_getDataFutureAsStream();
super.initState();
}
.
.
@override
void dispose() {
subscription!.cancel();
super.dispose();
}
}