简体   繁体   English

StreamBuilder 未更新 Flutter 中的 Firestore 数据

[英]StreamBuilder not updating Firestore data in Flutter

I'm making a Flutter application and I'm trying to get the user's data in the app.我正在制作一个 Flutter 应用程序,我正在尝试在应用程序中获取用户数据。

So basically, the user registers with his info (name, email, password), and this data is displayed in a ProfilePage when he's logged in.所以基本上,用户使用他的信息(姓名、email、密码)进行注册,当他登录时,这些数据会显示在ProfilePage中。

According to Firestore documentation, I'm supposed to use a StreamBuilder to get his data.根据 Firestore 文档,我应该使用StreamBuilder来获取他的数据。

At this point, everything works fine.此时,一切正常。

The problem is that when the user logs out and another user logs in, the ProfilePage displays the precedent user's data (the user logged out).问题在于,当用户注销而另一个用户登录时, ProfilePage显示先前用户的数据(用户已注销)。

Only if I restart the app, then I'm getting the right data.只有当我重新启动应用程序时,我才能获得正确的数据。

Here's my ProfilePage :这是我的个人ProfilePage

class UserInformation extends StatefulWidget {
  @override
  _UserInformationState createState() => _UserInformationState();
}

class _UserInformationState extends State<UserInformation> {

  final _uid = FirebaseAuth.instance.currentUser!.uid;

  final Stream<QuerySnapshot> _usersStream =
      FirebaseFirestore.instance.collection('Users')
        .doc(_uid)
        .collection('UserData')
        .snapshots();

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
       key: Key(_uid),
      stream: _usersStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return const Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Text("Loading");
        }

        return ListView(
          children: snapshot.data!.docs
              .map((DocumentSnapshot document) {
                Map<String, dynamic> data =
                    document.data()! as Map<String, dynamic>;
                return ListTile(
                  title: Text(data['full_name']),
                  subtitle: Text(data['company']),
                );
              })
              .toList()
              .cast(),
        );
      },
    );
  }
}

I see that this is a question asked several times on SO but I couldn't find a good solution.我看到这是一个在 SO 上被问过多次的问题,但我找不到好的解决方案。 I tried to add a unique key in the StreamBuilder but it doesn't solve the problem.我试图在StreamBuilder中添加一个唯一键,但它并没有解决问题。

I also saw the use of didUpdateWidget but I don't understand how to use it.我也看到了didUpdateWidget的使用,但我不明白如何使用它。

try replace this:尝试替换这个:

  final _uid = FirebaseAuth.instance.currentUser!.uid;

with this:有了这个:

  late final _uid;
  @override
  initState() {
  _uid = FirebaseAuth.instance.currentUser!.uid;
  super.initState();
 }

then restart your app again, and simulate your behavior然后重新启动您的应用程序,并模拟您的行为

reload the current user details with:使用以下命令重新加载当前用户详细信息:

await FirebaseAuth.instance.currentUser!.reload();

I will say that the best place to put it, is to do it before returning that stream, first make the Stream a method:我会说放置它的最佳位置是在返回 stream 之前执行此操作,首先使 Stream 成为一个方法:

Stream<QuerySnapshot> myStream() async {
await FirebaseAuth.instance.currentUser!.reload();
final _uid = FirebaseAuth.instance.currentUser!.uid;
return FirebaseFirestore.instance.collection('Users')
    .doc(_uid)
    .collection('UserData')
    .snapshots();
}

then in the StreamBuilder , set stream property to:然后在StreamBuilder中,将stream属性设置为:

stream: myStream(),

I found the solution:我找到了解决方案:

I simply moved the stream inside the build and the problem is solved !我只是将 stream 移到构建中,问题就解决了!

After edit:编辑后:

class UserInformation extends StatefulWidget {
  @override
  _UserInformationState createState() => _UserInformationState();
}

class _UserInformationState extends State<UserInformation> {

  @override
  Widget build(BuildContext context) {

 final _uid = FirebaseAuth.instance.currentUser!.uid;

  final Stream<QuerySnapshot> _usersStream =
      FirebaseFirestore.instance.collection('Users')
        .doc(_uid)
        .collection('UserData')
        .snapshots();

    return StreamBuilder<QuerySnapshot>(
       key: Key(_uid),
      stream: _usersStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return const Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Text("Loading");
        }

        return ListView(
          children: snapshot.data!.docs
              .map((DocumentSnapshot document) {
                Map<String, dynamic> data =
                    document.data()! as Map<String, dynamic>;
                return ListTile(
                  title: Text(data['full_name']),
                  subtitle: Text(data['company']),
                );
              })
              .toList()
              .cast(),
        );
      },
    );
  }
}
```

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Flutter 和 Firestore 中的新数据更新 StreamBuilder - Updating a StreamBuilder with new data in Flutter and Firestore Flutter:更新单个文档时,StreamBuilder 获取其他 Firestore 文档 - Flutter: StreamBuilder gets other firestore documents when updating a single document Flutter Firebase 查询 Firestore 和 Streambuilder() 的问题 - Flutter Firebase Problems with Query Firestore and Streambuilder() Flutter 云Firestore StreamBuilder<documentsnapshot> 错误</documentsnapshot> - Flutter cloud firestore StreamBuilder<DocumentSnapshot> error Flutter StreamBuilder 闪烁数据然后清除 - Flutter StreamBuilder flashes with data then clears 错误 state:使用 StreamBuilder 和 Firestore 时,快照在 flutter 中既没有数据也没有错误 - Bad state: Snapshot has neither data nor error in flutter when using StreamBuilder and Firestore Streambuilder 没有显示来自 firestore 的数据 - Streambuilder did not display the data from firestore 使用 StreamBuilder 从 Firestore 文档中获取数据 - Fetch data from Firestore Document using StreamBuilder 搜索词未从 TextField 更新到 Firestore StreamBuilder 调用 - Search Term not updating from TextField to Firestore StreamBuilder Call 从 flutter 应用程序在 firestore 中更新数据后无法读取数据 - Cannot read data after updating it in firestore from flutter app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM