Search code examples
serverdartfluttercallbloc

Flutter: Bloc dispose without waiting for the server response


As soon as the user enters in a page, a call to the server will be executed. If the snapshot has data, a stream will be send to the UI with which will create a ListView, otherwise, if the snapshot has an error, a stream error message will be sinked.

So, the call I have:

try {
      List answer = await call();
      createList.sink.add(answer);
    } on Exception catch (e) {
      createList.sink.addError(e);
    }

The problem is: if the connection is slow, and the user quits that page before the call is completed, the controllers will be disposed and the app will complain that the error cannot be sinked after that I've disposed the controller. So, is there a way to "abort" the call to the server when the user quits the page?


Solution

  • Using the controller's isClosed property, you could just check if the controller is closed before adding the events, like so:

    try {
      List answer = await call();
      if (!createList.isClosed) {
        createList.sink.add(answer);
      }
    } on Exception catch(e) {
      if (!createList.isClosed) {
        createList.sink.addError(e);
      }
    }