1

我正在尝试根据 StreamBuilder 返回的数据从 Firebase 实时数据库中获取其他数据。

Widget build(BuildContext context) {
var authBloc = Provider.of<AuthBloc>(context);
return Scaffold(
  body: SafeArea(
    bottom: false,
    left: false,
    right: false,
    child: Column(
      children: [
        StreamBuilder<User>(
          stream: authBloc.currentUser,
          builder: (context, snapshot) {
            if (!snapshot.hasData) return CircularProgressIndicator();
            //check if database has data for uid
            //if yes get data from uid for player
            //else create uid in database
            userData(snapshot.data);
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("${myPlayer.first.country}"),
                  SignInButton(
                    Buttons.Facebook,
                    text: 'Sign Out',
                    onPressed: () => authBloc.logout(),
                  )
                ],
              ),
            );
          },
        ),
        Text("${myPlayer.length}"),
      ],
    ),
  ),
);

}

函数 userData() 与 Firebase 实时数据库交互以获取数据,并且它能够成功地做到这一点,由正确的打印输出指示。

userData(userdata) async {
//Clear any previous entry to myPlayer
myPlayer.clear();
//Make a call to database to fetch details of all users
await databaseReference.child('users').once().then((data) {
  //By default assume user doesn't exist
  bool userexists = false;
  //Map the output
  if (data.value != null) {
    var dataMap = data.value;
    dataMap.forEach((key, value) {
      //if the userid exists in database
      if (key == userdata.uid) {
        //mark boolean to true
        userexists = true;
        //add values in database to the myPlayer
        myPlayer.add(global.Player(
          uid: key,
          displayName: value['displayName'],
          avatar: value['avatar'],
          email: value['email'],
          country: value['country'],
        ));
      }
    });
  }

  //if user doesn't exist and boolean is false
  if (!userexists) {
    //get User Country
    //add default values to myplayer
    myPlayer.add(global.Player(
      uid: userdata.uid,
      displayName: userdata.displayName,
      avatar: "default",
      email: userdata.email,
      country: country,
    ));
    //add default values to database table
    databaseReference.child('users').child(userdata.uid).set({
      'avatar': "default",
      'country': country,
      'email': userdata.email,
      'displayName': userdata.displayName,
    });
  }
});
print(myPlayer.first.country);

}

但是,在 StreamBuilder 小部件中它说

════════ Exception caught by widgets library ═══════════════════════════════════
Bad state: No element
The relevant error-causing widget was
StreamBuilder<User>
lib/home.dart:111

我是 StreamBuilder 的新手,如果有人能指导我如何解决这个问题,我将不胜感激。谢谢

4

0 回答 0