【问题标题】:async function that gets data from firestore executing multiple times in dart/flutter在 dart/flutter 中执行多次从 firestore 获取数据的异步函数
【发布时间】:2021-08-17 12:53:30
【问题描述】:

我在这里有一段代码应该从 firebase firestore 获取一些数据并将该数据添加到列表中,然后 listview.builder 使用该列表来使用项目列表更新 ui。但不知何故,相同的数据不断地一次又一次地添加到列表中。我放了一个打印语句,我可以看到“then”函数中的代码不断地执行。我如何阻止这种情况发生? 提前致谢

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

import '../models/reportmodel.dart';
import 'package:flutter/material.dart';

class AllReports extends StatefulWidget {
  @override
  _AllReportsState createState() => _AllReportsState();
}

class _AllReportsState extends State<AllReports> {
  List<Report> reportList = [];
  bool isLoading = true;

  @override
  Widget build(BuildContext context) {
    getData();
    return (isLoading)
        ? buildLoading()
        : ListView.builder(
            padding: EdgeInsets.all(20),
            itemBuilder: (context, index) {
              return Container(
                width: double.infinity,
                height: 140,
                child: Column(
                  children: [
                    Text(
                      "Complaint ID: " + reportList[index].getComplaintHash(),
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Name: " + reportList[index].getComplainantName(),
                    ),
                    Text("Time: " + reportList[index].getComplaintTime()),
                  ],
                ),
              );
            },
            itemCount: reportList.length);
  }

  Widget buildLoading() => Stack(
        fit: StackFit.expand,
        children: [
          Center(child: CircularProgressIndicator()),
        ],
      );

  void getData() async {
    final user = FirebaseAuth.instance.currentUser;
    final snapshot = await FirebaseFirestore.instance
        .collection(user.email)
        .getDocuments()
        .then((snapshot) {
      for (int i = 0; i < snapshot.documents.length; i++) {
        reportList.add(Report.addData(
            snapshot.documents[i].id.toString(),
            snapshot.documents[i].data()["name"].toString(),
            snapshot.documents[i].data()["contact"].toString(),
            snapshot.documents[i].data()["time"].toString(),
            snapshot.documents[i].data()["description"].toString(),
            snapshot.documents[i].data()["additional_info"].toString()));
      }
      this.setState(() {
        isLoading = false;
      });
    });
  }
}

【问题讨论】:

  • 嗨,那里。我只是想问一下您的数据中有多少项?因为我认为“getData()”内部的循环是问题的原因。

标签: firebase flutter dart firebase-realtime-database async-await


【解决方案1】:

它被一遍又一遍地执行,因为你在 build() 内部调用方法 getData(),每次调用 setState 时它都会发出另一个构建。因此,方法 getData() 将继续执行并且检索数据。

您应该使用FutureBuilder 小部件来处理异步操作。

https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

【讨论】:

  • 本来想写一样的,但正如德国谚语所说:“早起的鸟儿有虫吃”
猜你喜欢
  • 2020-11-14
  • 2021-08-27
  • 1970-01-01
  • 2020-08-01
  • 2021-08-17
  • 2020-09-04
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多