Home > Back-end >  Show Widget for reload when timeout on StreamBuilder Flutter
Show Widget for reload when timeout on StreamBuilder Flutter

Time:08-12

I'm fetching data using a Future http request method and display everything using an StreamBuilder which just works fine. Now I want a reload widget to be shown when the requests times out. Currently my StreamBuilder looks like this:

StreamBuilder(
  stream: Stream.fromFuture(makeHttpRequest()),
  builder: (context, AsyncSnapshot<List<models.Tutorial>> snapshot) {
    if (snapshot.hasData) {
      // show requested data
    }
    return LoadingAnimationWidget.fourRotatingDots(
        color: const Color(0xFF465770), size: 45);
  });

I could add a timeout to the http request method or the stream itself but I wasn't able to display a reload dialog on timeout. How could I implement that?

CodePudding user response:

You say that you know how to add a timeout to the Stream, which is already halfway to the solution:

stream: Stream.fromFuture(makeHttpRequest()).timeout(const Duration(seconds: TIME_OUT_IN_SECONDS),
            onTimeout: (controller) {
          controller.addError(ERROR_CAN_BE_ANY_OBJECT);
        }),

Then in your builder, you can check snapshot.hasError, then snapshot.error is the error that you've set in the onTimeout callback. If so, it suggests that a timeout has happened, and you can show your dialog.

  • Related