FlutterPaginator icon indicating copy to clipboard operation
FlutterPaginator copied to clipboard

Cancel future on dispose()

Open philipgiuliani opened this issue 4 years ago • 5 comments

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()

philipgiuliani avatar Jun 29 '20 08:06 philipgiuliani

Did you solved it? If yes, how?

tomasweigenast avatar Jul 23 '20 21:07 tomasweigenast

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 avatar Jul 24 '20 06:07 philipgiuliani

@philipgiuliani Can you provide a code sample, please? I think I did it, but I want to make sure. Thank you

tomasweigenast avatar Jul 24 '20 11:07 tomasweigenast

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.

hacker1024 avatar Aug 23 '20 02:08 hacker1024

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();
  }
}

SonPatrick avatar May 06 '22 19:05 SonPatrick