为什么我的Flutter应用程序无法获取Firebase实时数据库中的更新数据?

zzzyeukh  于 2022-11-17  发布在  Flutter
关注(0)|答案(2)|浏览(208)

目前,我正在做一个flutter项目,使用Firebase中的Realtime Database。这个应用程序有一个更新用户详细信息的功能。我已经成功实现了更新功能,因为它在更新后立即存储在数据库中。但是,当我回到查看个人资料页面时,正在显示的详细信息尚未更新。我需要先转到其他选项卡,然后返回“查看配置文件”页面,在该页面中将加载更新的数据。为什么会有延迟?它不应该是实时的吗?一旦我更新了数据?任何帮助将不胜感激。谢谢!

以下是我的代码,用于显示当前用户的信息:

static void readCurrentOnlineUserInfo() async
  {

    final FirebaseAuth fAuth = FirebaseAuth.instance;
    User? currentFirebaseUser;

    currentFirebaseUser = fAuth.currentUser;

    DatabaseReference userRef = FirebaseDatabase.instance
        .ref()
        .child("passengers")
        .child(currentFirebaseUser!.uid);

    userRef.once().then((snap)
    {
      if(snap.snapshot.value != null)
      {
        userModelCurrentInfo = UserModel.fromSnapshot(snap.snapshot);
        print("name" + userModelCurrentInfo!.first_name.toString());
        print("username" + userModelCurrentInfo!.username.toString());
      }
    });
  }

另一方面,这是我用来在应用程序中显示数据的代码:

import 'package:firebase_database/firebase_database.dart';

class UserModel
{
  String? first_name;
  String? last_name;
  String? id;
  String? email;
  String? username;
  String? password;
  String? phoneNum;

  UserModel({this.first_name, this.last_name, this.id, this.email, this.username, this.password, this.phoneNum});

  UserModel.fromSnapshot(DataSnapshot snap)
  {
    first_name = (snap.value as dynamic)["first_name"];
    last_name = (snap.value as dynamic)["last_name"];
    id = snap.key;
    email = (snap.value as dynamic)["email"];
    username = (snap.value as dynamic)["username"];
    password = (snap.value as dynamic)["password"];
    phoneNum = (snap.value as dynamic)["phoneNum"];
  }
}

我在小部件中显示上述信息,如下所示:

UserAccountsDrawerHeader(
                decoration: BoxDecoration(
                  color: Color(0xFFFED90F),
                ),
                accountName: new Text(userCurrentModelInfo!.first_name,
                  style: TextStyle( color: Colors.white,
                    fontSize: 15,
                    fontFamily: "Montserrat",
                    fontWeight: FontWeight.w600,),
                ),
8yoxcaq7

8yoxcaq71#

不要使用Future Builder获取实时更新使用stream builder获取实时更新
这就是为什么当你进入另一个屏幕时会得到数据,当你使用流构建器返回时,它总是检查DB中是否有新数据,并显示新数据

ajsxfq5m

ajsxfq5m2#

问题是您使用了once,它只读取数据一次(因此得名)。
如果你想更新数据的变化,使用onValue,如文档中关于阅读数据的说明所示。这也意味着你必须将数据库中的数据存储在小部件的状态中,或者使用StreamBuilder来显示它(因为onValue返回Stream)。
关于使用StreamBuilder显示Firebase的其他数据库的实时更新的示例,请查看本文档中关于监听实时更新的第二个代码片段。在使用FirebaseFirestore.instance.collection('users').snapshots();的地方,您需要使用您的onValue

相关问题