Search code examples
firebaseflutterfuturebuilder

flutter: red screen caused by future builder


My flutter-firebase app starts with checking a user's state. If the user is a pro, mypagepro screen will show up, else mypage will show up. Here is my code for that.

@override
Widget build(BuildContext context) {
  return FutureBuilder(
      future: FirebaseFirestore.instance
          .collection('crews')
          .doc(user.uid)
          .get(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.data['isPro'] == true) {
          return MyPagePro();
        } else {
          return MyPage();
        }
      });
    }
  }
}

Problem is that it takes so long to check the user's state that a red screen shows up before finally showing mypage or mypagepro screen.

enter image description here

I want to show mypage or mypagepro screen without showing any red screen like this. How can I avoid this red screen while checking a user's state?


Solution

  • You should check if snapshot has data.

    Try this:

    @override
    Widget build(BuildContext context) {
      return FutureBuilder(
          future: FirebaseFirestore.instance
              .collection('crews')
              .doc(user.uid)
              .get(),
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            if (snapshot.hasData && snapshot.data['isPro'] == true) {
              return MyPagePro();
            } else {
              return MyPage();
            }
          });
        }
      }
    }