2

What's the right way to generate a snapshot.error for a FutureBuilder? I've a singleton to handle http requests, with a method:

try {
  var response = await http.get(url);

  // Success
  if (response.statusCode == 200) {
      [...]
  }
  // Failure
  else {
    return Future.error("Error");
  }
} catch (e) {
  return Future.error("Error");
}

On the other side I've a widget with a FutureBuilder:

FutureBuilder(
      future: new Future(() => {Singleton().request()}),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
            // snapshot has ALWAYS data even if I return error
        } else if(snapshot.hasError) {
            // never reach this statement
        }
      });

What am I doing wrong? Could you please point me in the right direction to handle errors? I'd like to avoid the callback catchError(). Thanks in advance.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
Jumpa
  • 4,319
  • 11
  • 52
  • 100

1 Answers1

0

It's because if a snapshot has an error it will mean the snapshot has data and so the else if statement will never be reached. You should first check for any error and then for the data.

Like this -

FutureBuilder(
      future: new Future(() => {Singleton().request()}),
      builder: (context, snapshot) {
        if (snapshot.hasError) {
            // do something
        } else if(snapshot.hasData) {
            // do something
        }
      });
SuPythony
  • 875
  • 8
  • 23