【问题标题】:Retrive a data from firebase database with Timer使用 Timer 从 firebase 数据库中检索数据
【发布时间】:2020-07-22 08:19:48
【问题描述】:

如何在 Flutter 应用中使用 Timer 功能从 firebase 数据库中检索数据?

P.S.用户请求数据将在 5 分钟后从 firebase 数据库中检索出来。

谢谢

【问题讨论】:

    标签: database firebase flutter timer


    【解决方案1】:

    我的代码如下所示。正如您在上面指出的那样,我也更新了数据库,但仍然是白屏

    Widget build(BuildContext context) {
    return Scaffold(
        body: StreamBuilder(
            stream: Firestore.instance
                .collection('fortunepool')
                .where('index', isGreaterThanOrEqualTo: 0)
                .orderBy('index')
                .limit(1)
                .snapshots(),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return Container(child: CircularProgressIndicator());
              } else {
                return ListView.builder(
                    itemCount: snapshot.data.documents.length,
                    itemBuilder: (context, index) {
                      List<DocumentSnapshot> listedQS =
                          snapshot.data.documents; //listed documents
    
                      DocumentSnapshot mypost = listedQS[0];
                      return Stack(
    

    【讨论】:

      【解决方案2】:

      那么你通过调用where('index' isEqualTo: ' 0' 所做的事情是它首先找到任何具有上述索引字段的文档,然后它只返回值等于你提供的值的文档

      【讨论】:

      • 你看不到
      【解决方案3】:
      @override
        Widget build(BuildContext context) {
          return Scaffold(
              body: StreamBuilder(
                  stream: Firestore.instance.collection('fortunepool').where('index', isGreaterThanOrEqualTo: 0).orderBy('index').limit(1).snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      return Container(child: CircularProgressIndicator());
                    } else {
                      return ListView.builder(
                          itemCount: snapshot.data.documents.length,
                          itemBuilder: (context, index) {
                            List<DocumentSnapshot> listedQS =
                                snapshot.data.documents; //listed documents
                            var random = new Random(); //dart math
                            for (var i = listedQS.length - 1; i > 0; i--) {
                              var n = random.nextInt(i + 1);
                              var temp = listedQS[i];
                              listedQS[i] = listedQS[n];
                              listedQS[n] = temp;
                            }
                            DocumentSnapshot mypost = listedQS[0];
                            return Stack(
      

      【讨论】:

      • 那是因为你需要使用带有 where 查询的索引
      • 当您向数据库添加条目时,请使用类似于上面的 addEntry 函数,因此每个文档都有一个从 0、1、2、3 开始的索引,...然后您的 StreamBuilder 将听Firestore.instance .collection('//Collection name') .where('index', isGreaterThanOrEqualTo: 0) .orderBy('index') .limit(1) .snapshots(),
      • 对不起,我不能清楚地解释这一点,随机数是在你完成后从 firebase 获取文件再次检查stackoverflow.com/questions/46798981/…
      • 这可能是因为您没有为 firebase 中的项目添加实际索引,因此您的文档中必须有一个索引字段
      • 你为什么不接受下面的答案,现在它不适合你吗?
      【解决方案4】:

      我的代码如下所示,如何使用 Querysnapshot 方法显示文本和图像值?您在 brew 代码中提到的内容!我无法使用您的代码结构如下...

      您的代码:@wcyankees424

         snapshot = await Firestore.instance
            .collection('//Collection name')
            .where('index', isGreaterThanOrEqualTo: 0)
            .orderBy('index')
            .limit(1)
            .getDocuments();
      

      我的代码:

      body: StreamBuilder(
              stream: qs.collection('collection').limit(1).snapshots(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  const Text('Loading');
                } else {
                  return ListView.builder(
                      itemCount: snapshot.data.documents.length,
                      itemBuilder: (context, index) {
                        List<DocumentSnapshot> listedQS =
                            snapshot.data.documents; //listed documents
                        var random = new Random(); //dart math
                        for (var i = listedQS.length - 1; i > 0; i--) {
                          var n = random.nextInt(i + 1);
                          var temp = listedQS[i];
                          listedQS[i] = listedQS[n];
                          listedQS[n] = temp;
                        }
                        DocumentSnapshot mypost = listedQS[0];
                        return Stack(
                          children: <Widget>[
                            Container(
                              width: MediaQuery.of(context).size.width,
                              height: 350,
                              child: Padding(
                                padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
                                child: Material(
                                  color: Colors.white,
                                  elevation: 14.0,
                                  shadowColor: Color(0x882196F3),
                                  child: Center(
                                    child: Padding(
                                      padding: EdgeInsets.all(8.0),
                                      child: Column(
                                        children: <Widget>[
                                          Container(
                                            width:
                                                MediaQuery.of(context).size.width,
                                            height: 200,
                                            child: Image.network(
                                                '${mypost['image']}',
                                                fit: BoxFit.fill),
                                          ),
                                          SizedBox(height: 10.0),
                                          Text(
                                            '${mypost['title']}',
                                            style: TextStyle(
                                                fontSize: 20.0,
                                                fontWeight: FontWeight.bold),
                                          ),
                                          SizedBox(height: 10.0),
                                          Text(
                                            '${mypost['subtitle']}',
                                            style: TextStyle(
                                                fontSize: 16.0,
                                                fontWeight: FontWeight.bold,
                                                color: Colors.blueGrey),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ),
      

      【讨论】:

        【解决方案5】:
         Future<void> addEntry(Brew newBrew) async {
            //value you want saved are stored in newBrew and passed in
            Map<String, Object> entryData = {
              'name': newBrew.name,
              'strength': newBrew.strength,
              'sugars': newBrew.sugars,
              'index': newBrew.index,
            };
            await Firestore.instance.collection('//collection name').add(entryData);
          }
        
         Future<Brew> getEntries(Brew newBrew) async {
            QuerySnapshot snapshot = await Firestore.instance
                .collection('//Collection name')
                .where('index', isGreaterThanOrEqualTo: Random().nextInt('//this number should be higher than the number of documents'))
                .orderBy('index')
                .limit(1)
                .getDocuments();
        
            if (snapshot.documents.isNotEmpty) {
              Map<String, dynamic> documentData = snapshot.documents[0].data;
        
              return Brew(
                strength: documentData['strngth'],
                sugars: documentData['sugars'],
                name: documentData['name'],
                index: documentData['index'],
              );
            } else {
              snapshot = await Firestore.instance
                  .collection('//Collection name')
                  .where('index', isGreaterThanOrEqualTo: 0)
                  .orderBy('index')
                  .limit(1)
                  .getDocuments();
        
              Map<String, dynamic> documentData = snapshot.documents[0].data;
        
              return Brew(
                strength: documentData['strngth'],
                sugars: documentData['sugars'],
                name: documentData['name'],
                index: documentData['index'],
              );
            }
          }
        
        class Brew {
          final String name;
          final String sugars;
          final int strength;
          final int index;
        
          Brew({
            this.name,
            this.sugars,
            this.strength,
            this.index,
          });
        }
        

        您将为每个调用的索引创建一个字段,该索引将从 0 开始,为您数据库中的每个条目递增 1。 This might help you

        【讨论】:

        • 我想问你点别的。我的数据库中有 100 个文档。我想将 1 个文档随机重试给唯一用户。我的意思是,如果相同的用户请求检索文档,代码将从剩余的 99 个文档中选择并检索数据。我怎样才能做到这一点?
        • 很遗憾没有?
        • 你能按答案上的向上箭头吗?请回答按钮只是切换答案。我也更新了我的答案
        • 谢谢。我会试试这个?
        • 我添加了更多代码我创建了一个示例类,你显然可以用你自己的类代替我希望这对你来说清楚。
        【解决方案6】:
          Future.delayed(Duration(minutes: 5), () {
              Timer.periodic(Duration(minutes: 5), (Timer t) {
                setState(() {});
              });
            });
        
        

        好的,把它和你一起放在有状态的小部件中 StreamBuilder 这在我的模拟器上工作。让我知道它是否适合你。

        【讨论】:

        • 不幸的是它没有用。你可以在下面看到我的代码
        • 我有一些不同的东西让你试试
        • 是的,它起作用了,但不是我想要的方式。实际上,一开始我不想看到从 Firebase 数据库(木板页面)检索到的任何帖子。用户定时器请求后会工作,5分钟后不会再自动取回数据。目的是在请求 5 分钟后通过用户请求检索数据。在用户提出新请求之前不会有任何数据检索:) 它不会是周期性的。再次非常感谢您的支持!等待您的答复...
        • 我改变了它它不一样它非常相似但我将它包裹在Future.delayed
        • 如果你不介意的话,我会把它添加到另一个答案中,所以我可以得到一些额外的帮助
        【解决方案7】:

        我的代码如下所示,但它不适用于您的代码。@wcyankees424

        body: StreamBuilder(
                stream: qs.collection('collection').snapshots(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    const Text('Loading');
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.documents.length,
                        itemBuilder: (context, index) {
                          List<DocumentSnapshot> listedQS = snapshot.data.documents;
                          var random = new Random();
                          for (var i = listedQS.length - 1; i > 0; i--) {
                            var n = random.nextInt(i + 1);
                            var temp = listedQS[i];
                            listedQS[i] = listedQS[n];
                            listedQS[n] = temp;
                          }
        
                          DocumentSnapshot mypost = listedQS[0];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-16
          • 2018-12-22
          • 1970-01-01
          相关资源
          最近更新 更多