flutterdartflutter-futurebuilder

FutureBuilder weird behaviour


I have a FutureBuilder which the future is this :

Future<Tutor> future(Object? args) async {
    print("running future ...${args}");

    String title = "";
    String content = "";

    final SharedPreferences prefs = await SharedPreferences.getInstance();

    if (args != null) {
      debugPrint("args is not null ");

      title = (args as Tutor).title;
      content = args.content;

      await prefs.setString("title", title);
      await prefs.setString("content", content);
    } else {
      debugPrint("reading from cache..");

      title = prefs.getString("title") ?? "";
      content = prefs.getString("content") ?? "";
    }

    return Tutor(title, content);
  }

  return FutureBuilder(
        future: future(args),
        builder: ((context, snapshot) {
          WebViewController controller = WebViewController();

          debugPrint("Future is done ...");
       // the rest

But what I get is :

running future ...null

(2) Future is done ...

I don't get any of this prints:

debugPrint("args is not null "); // if
debugPrint("reading from cache.."); // else

It seems neither "if" nor "else" are executed.


Solution

  • Although this problem was solved auttomatically after one day but I should mention for next googlers that I also encountered this in another project and I figured that FutureBuilder has a inner error handler so it doesn't throw exceptions if something goes wrong with your "future" method. If you want to see what is what, you should always use try{}catch{} inside the future method or check snapshot.hasError to see if everything is OK.