【问题标题】:Flutter FutureBuilder calling function continuouslyFlutter FutureBuilder 不断调用函数
【发布时间】:2023-03-05 08:53:01
【问题描述】:

我有一个简单的功能,即从 Firestore 调用数据并过滤数据。但问题是我的未来构建器一直处于加载程序的情况(数据被成功调用,我可以在控制台中看到,但现在显示在未来)我认为这是因为我的功能正在循环调用或者我试图在我的函数中打印一些东西,这表明我我的功能没有停止,这就是为什么我认为我的 futureBuilder 会继续加载。

我的代码

  Future<List> getCustomerList() async {
    print('calling');
    String uUid1 = await storage.read(key: "uUid");
    String uName1 = await storage.read(key: "uName");
    String uNumber1 = await storage.read(key: "uNumber");

    setState(() {
      uUid = uUid1;
      uName = uName1;
      uNumber = uNumber1;
    });

    CollectionReference _collectionRef =
        FirebaseFirestore.instance.collection('Customers');
    QuerySnapshot querySnapshot = await _collectionRef.get();

    // Get data from docs and convert map to List
    List allData = querySnapshot.docs
        .where((element) => element['sellerUID'] == uUid)
        .map((doc) => doc.data())
        .toList();
    double gGive = 0;
    double gTake = 0;
    double gCal = 0;

    for (int i = 0; i < allData.length; i++) {
      // print(allData[i]);

      // print('give ${double.parse(allData[i]['give'].toString()) }');
      // print('take ${double.parse(allData[i]['take'].toString()) }');
      double.parse(allData[i]['give'].toString()) -
                  double.parse(allData[i]['take'].toString()) >
              0
          ? gGive += double.parse(allData[i]['give'].toString()) -
              double.parse(allData[i]['take'].toString())
          : gTake += double.parse(allData[i]['give'].toString()) -
              double.parse(allData[i]['take'].toString());
    }

    // print(gGive);
    // print(gTake);

    setState(() {
      Gtake = gGive.toString().replaceAll("-", "");
      Ggive = gTake.toString().replaceAll("-", "");
    });

    if (greenBox) {
      var check = allData.where((i) => i['take'] > i['give']).toList();

      return check;
    } else if (redBox) {
      var check = allData.where((i) => i['give'] > 1).toList();
      return check;
    } else {
      return allData;
    }
  }

我的 futureBuilder 看起来像这样

 Expanded(
  child: Container(
    height: Height * 0.5,
    child: FutureBuilder(
        future: getCustomerList(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            list = snapshot.data;
            return SingleChildScrollView(
              child: Column(
                children: [
                  
                  Container(
                    height: Height * 0.5,
                    child: ListView.builder(
                      shrinkWrap: true,
                      itemCount: list.length,
                      itemBuilder:
                          (BuildContext context,
                              int index) {
                        var showThis = list[index]
                                ['give'] -
                            list[index]['take'];

                        return list[index]
                                    ['customerName']
                                .toString()
                                .contains(searchString)
                            ? GestureDetector(
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            CustomerData(
                                                data: list[
                                                    index])),
                                  );
                                },
                                child: Padding(
                                  padding:
                                      const EdgeInsets
                                              .only(
                                          left: 13,
                                          right: 13),
                                  child: Container(
                                    decoration:
                                        BoxDecoration(
                                      border: Border(
                                          top: BorderSide(
                                              color: Colors
                                                  .grey,
                                              width:
                                                  .5)),
                                    ),
                                    child: Padding(
                                      padding:
                                          const EdgeInsets
                                                  .all(
                                              13.0),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment
                                                .spaceBetween,
                                        children: [
                                          Row(
                                            children: [
                                              CircleAvatar(
                                                child:
                                                    Text(
                                                  list[index]['customerName'][0]
                                                      .toString(),
                                                  style:
                                                      TextStyle(fontFamily: 'PoppinsBold'),
                                                ),
                                                backgroundColor:
                                                    Color(0xffF7F9F9),
                                              ),
                                              SizedBox(
                                                width:
                                                    20,
                                              ),
                                              Text(
                                                list[index]['customerName']
                                                    .toString(),
                                                style: TextStyle(
                                                    fontFamily:
                                                        'PoppinsMedium'),
                                              ),
                                            ],
                                          ),
                                          Text(
                                            'RS ${showThis.toString().replaceAll("-", "")}',
                                            style: TextStyle(
                                                fontFamily:
                                                    'PoppinsMedium',
                                                color: list[index]['give'] - list[index]['take'] <
                                                        0
                                                    ? Colors.green
                                                    : Colors.red),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ),
                              )
                            : Container();
                      },
                    ),
                  )
                ],
              ),
            );
          } else
            return Center(
              heightFactor: 1,
              widthFactor: 1,
              child: SizedBox(
                height: 70,
                width: 70,
                child: CircularProgressIndicator(
                  strokeWidth: 2.5,
                ),
              ),
            );
        }),
  ),
),

我很确定这是因为 futurebuilder 一直在调用正在返回数据的函数,但由于一直在调用函数,我的 Futurebuilder 一直在显示加载。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您不应该在您提供给 FutureBuilder 的未来内调用 setState。

    状态实现将导致 FutureBuilder 重新构建。意味着再次触发未来,还有……无限循环!

    【讨论】:

    • 谢谢,但在此问题之后,它不会更改列表数据。意味着它只是调用函数一次问题是我的数据正在更新,我需要更新 Future 列表,为此我需要在几秒钟内而不是继续调用该函数
    • 那么你可能不应该使用 FutureBuilder !只需将未来的结果存储在您的状态内的变量中。并使用 setState 和 Stream.periodic 刷新变量。如果这对你来说听起来很“奇怪”,我可以举一个小例子。
    猜你喜欢
    • 2020-01-07
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 2019-11-03
    • 2021-10-08
    • 2021-10-23
    相关资源
    最近更新 更多