【问题标题】:How to update the future in FutureBuilder to get new data while using GetX如何在使用 GetX 时更新 FutureBuilder 中的未来以获取新数据
【发布时间】:2021-06-05 20:11:55
【问题描述】:

我正在使用 GetX 和 FutureBuilder 从我的数据库中构建卡片列表。 假设我在 DB 中有 10 种产品,然后显示 10 张卡。当我再添加一个产品时,主屏幕上的卡片没有更新,我必须导航进出页面才能显示第 11 个产品。

如何强制更新,即可能制作一个“刷新”按钮来加载最新数据。

PS:我不想使用 STREAM-BUILDER,因为我不想主动听取所有更改,但仅在需要时才使用。我也不能使用 SetState(),因为我正在使用 GetX,因此没有 StatefulWidget。

这是我的卡片类:

FutureBuilder(
                future: databaseController.getData()
                builder: (context, snapshot) {
                   return StaggeredGridView.countBuilder(
                      itemCount: snapshot.data.length,
                      crossAxisCount: 2,
                      itemBuilder: (BuildContext context, int index) =>
                          GetX<FindDeviceLocation>(builder: (controller) {
                        return CreateTheCard(
                            lindex: index,
                            location: snapshot.data[index]["location"],
                            summary: snapshot.data[index]["summary"],
                            description: snapshot.data[index]["description"],
                            category: snapshot.data[index]["category"],
                            imageURL: snapshot.data[index]["adImage"],
                            
                            onTapFunction: () => Get.to(DetailPage(
                                  post: snapshot.data[index],
                                )));
                      }),

这是我从数据库中获取数据的方法:

Future getData() async {
    QuerySnapshot _firebaseDb = await FirebaseFirestore.instance
        .collection("items")
        .where("status", isEqualTo: true)
        .orderBy("postTime", descending: true)
        .get();
          
    return _firebaseDb.docs;
  }

【问题讨论】:

  • 创建一个 bool obs 变量。var gettingDataCompleted = false.obs 并在 builder 内部检查它以进行重建。

标签: flutter dart flutter-futurebuilder flutter-getx


【解决方案1】:

使用 getx 工作者 曾经: 如果数据发生变化,您可以更新视图

ever(index, (value) {

// 在这里调用你的函数 // 此处的任何代码都将在索引更改时被调用 });

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2021-02-23
    • 2021-05-11
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2023-04-04
    • 2020-05-08
    相关资源
    最近更新 更多