firebase FutureBuilder未在Flutter中构建异步

hvvq6cgz  于 2023-01-18  发布在  Flutter
关注(0)|答案(1)|浏览(110)

我有一个FutureBuilder,它的未来是从Firestore请求一个布尔值。但是当我更新这个值时(hasAccountSetup变为true),什么都没有发生,直到我快速重新加载应用程序。
我不知道在这种情况下是否应该使用FutureBuilder,但目标是在我将firebase数据库中的hasAccountSetup更新为true后,应用程序立即返回HomePage()。

Future<bool> _getCurrentUserData() async {
  final DocumentSnapshot userDoc = await FirebaseFirestore.instance
      .collection('Users')
      .doc(Auth().currentUser!.uid)
      .get();

  return userDoc.get('HasSetupAccount');
}

class _WidgetTreeState extends State<WidgetTree> {
  @override
  //construtor da class?
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: Auth().authStateChanges,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return FutureBuilder(
              future: _getCurrentUserData(),
              builder: ((context, AsyncSnapshot<bool> hasAccountSetup) {
                if (hasAccountSetup.data == true) {
                  return MyHomePage();
                } else {
                  return AccountSetup();
                }
              }));
        } else {
          return LoginPage();
        }
      },
    );
  }
agxfikkp

agxfikkp1#

您正在使用StreamBuilder,但流不是stream,而是future
请看streamBuilder的示例:如果没有reload,您可以在这里直接监听文档中发生的任何更改。根据您的需要调整此设置。

class _UserInformationState extends State<UserInformation> {
  final _usersStream = FirebaseFirestore.instance
      .collection('Users')  // 👈 Change the collection name according to your need 
      .doc(Auth().currentUser!.uid) // 👈 change the document id according to your need
      .snapshots();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
          stream: _usersStream,
          builder:
              (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (snapshot.hasError) {
              return const Text('Something went wrong');
            }
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Text("Loading");
            }
            Map<String, dynamic> data =
                snapshot.data!.data()! as Map<String, dynamic>;
            return Text(data['fullName']);
          },
        ),
      ),
    );
  }
}

相关问题