从实时Firestore文档中获取数据

时间:2020-04-15 13:40:51

标签: firebase flutter dart google-cloud-firestore

我看到StreamBuilder小部件可以解决类似的问题和答案。

就我而言,当我实现它时,我的代码不会等待获取数据而只是继续前进(就我而言,应用程序跳至下一页)。因此,我是否需要构建StreamBuilder窗口小部件,或者是否有一种简单的方法可以实时获取并获取数据?

我注意到我没有将asterisc与 async * 一起使用,但如果这样做,则身份验证将无法正常工作。

说明:

该代码未输入以下行:

if (!snapshot.hasData)
 return new Text('Loading...');
return new Text(
  snapshot.data.data['name']
 );

此外,print(test);语句显示以下内容:

StreamBuilder<DocumentSnapshot>

这是整个部分:

onPressed: () async {
  setState(() {
    showSpinner = true;
  });
  try {
    LoginScreen.user =
        await _auth.signInWithEmailAndPassword(
            email: email, password: password);
    if (LoginScreen.user != null) {
      // get the users data and save them
      if (LoginScreen.user.user.uid !=
          'IDVwQXAsZas213Va0OIH2IsoU5asdaTfraBJ2') {
      Widget test = await StreamBuilder<DocumentSnapshot>(
          stream: _firestore
              .collection('Employees')
              .document(LoginScreen.user.user.uid)
              .snapshots(),
          builder: (BuildContext context,
              AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (!snapshot.hasData)
              return new Text('Loading...');
            return new Text(
              snapshot.data.data['name']
            );
          },
        );
        print(test);
        Navigator.pushReplacementNamed(
            context, TabCreator.screenId);
      } else {
      }
    }
  } catch (e) {
    print(e);
    // when getting an erro stop spinner
    setState(() {
      showSpinner = false;
    });
  }
}

更新

我创建了一个新的标准flutter项目,以查看我的代码中是否还有其他东西弄乱了StreamBuilder。我仍然没有输出。

另一方面,当我在onPressed方法中实现以下代码时,我得到了想要的结果:

替代解决方案:

onPressed: () {
  DocumentReference documentReference = await Firestore.instance
      .collection('Employees')
      .document('8nss0gppzNfOBMuRz9H44dv7gSd2');
  documentReference.snapshots().listen((datasnapshot) {
    if (datasnapshot.exists) {
      print(datasnapshot.data['name'].toString());
    } else {
      print('Error!');
    }
});
}

以下是在标准Flutter项目中实现的实现的 StreamBuilder

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _auth = FirebaseAuth.instance;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              'Testing',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // DocumentReference documentReference = await Firestore.instance
          //     .collection('Employees')
          //     .document('8nss0gppzNfOBMuRz9H44dv7gSd2');
          // documentReference.snapshots().listen((datasnapshot) {
          //   if (datasnapshot.exists) {
          //     print(datasnapshot.data['name'].toString());
          //   } else {
          //     print('Error!');
          //   }
          // });
          StreamBuilder<DocumentSnapshot>(
            stream: Firestore.instance
                .collection('Employees')
                .document('8nss0gppzNfOBMuRz9H44dv7gSd2')
                .snapshots(),
            builder: (BuildContext context,
                AsyncSnapshot<DocumentSnapshot> snapshot) {
              if (snapshot.hasError)
                return new Text('Error: ${snapshot.error}');
              switch (snapshot.connectionState) {
                case ConnectionState.waiting:
                  return new Text('Loading...');
                default:
                  return new Text(snapshot.data.data['name']);
              }
            },
          );
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:1)

将代码更改为以下内容:

builder: : (BuildContext context,
              AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (!snapshot.hasData){
              return new Text('Loading...');
          }
          else{
              print(snapshot);
              Navigator.pushReplacementNamed(
                   context, TabCreator.screenId);
           }

添加一个else块,以便在您有数据时进入else并导航到页面。


此外,您需要在StreamBuilder方法内使用build,而不是在用于处理数据处理的onPressed函数内使用。例如,您可以执行以下操作:

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  bool visible = false;
  final firestoreInstance = Firestore.instance;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            Visibility(
              child: StreamBuilder<DocumentSnapshot>(
                stream: Firestore.instance
                    .collection('users')
                    .document('FIJbBBiplAGorYzdtUQF')
                    .snapshots(),
                builder: (BuildContext context,
                    AsyncSnapshot<DocumentSnapshot> snapshot) {
                  print(snapshot);
                  if (snapshot.hasError)
                    return new Text('Error: ${snapshot.error}');
                  else if (snapshot.hasData) {
                    print(snapshot.data.data);
                    return new Text(snapshot.data.data["age"].toString());
                  }
                  return new CircularProgressIndicator();
                },
              ),
              visible: visible,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            visible = true;
          });
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

因此,在这里我也使用Visibility()小部件将其隐藏,但是当单击FAB按钮时,将显示来自Firestore的数据。