Получение дополнительных данных из базы данных Realtimedatabase

Я пытаюсь получить дополнительные данные из базы данных Firebase Realtime на основе данных, возвращаемых StreamBuilder.

      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 Realtime для получения данных, и она может делать это успешно, о чем свидетельствует правильный вывод на печать.

      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 и был бы признателен, если бы кто-нибудь любезно посоветовал мне решить эту проблему. Спасибо

0 ответов

Другие вопросы по тегам