Flutter:Future 函数正在连续调用

标签 flutter future provider

我使用 future 函数从 API 检索数据,并使用 Consumer 来包装它,因为只有当数据发生更改时,我的列表才会更新。我的代码工作正常,但我 future 的函数正在不断调用。 我的代码如下

                    Consumer<Category>(
                      builder: (context, category, child) {
                        return FutureBuilder(
                            future: category.getAllCategories(), //returns a list
                            builder: (BuildContext context, AsyncSnapshot snapshot) {
                              if (!snapshot.hasData || snapshot.data.isEmpty) {
                                return Center(
                                  child: Container(
                                    child: CircularProgressIndicator(),
                                  ),
                                );
                              } else {
                                return ListView.builder(
                                    scrollDirection: Axis.horizontal,
                                    itemCount:
                                        category.getlength != 0 || category.getlength != null || !category.getAllCatisempty ? category.getlength : 0,
                                    shrinkWrap: true,
                                    itemBuilder: (context, index) {
                                      return InkWell(
                                        onTap: () async {
                                          try {

                                            print('connection Status ${await DataConnectionChecker().connectionStatus}');
                                            setState(() {

                                              _selectedIndex = index;
                                              timeCount = 0;

                                            });

                                            productsProvider.clearProductList();
                                            productsProvider.getAllProductsInCategory(category.allCategoryList[index].catId);

                                            setState(() {
                                              catId = category.allCategoryList[index].catId;
                                            });
                                          } catch (e) {
                                            print('exception category click $e');
                                          }
                                        },
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.center,
                                          children: <Widget>[
                                            Card(
                                              color: _selectedIndex != null && _selectedIndex == index ? selectedColor : defColor,
                                              elevation: _selectedIndex != null && _selectedIndex == index ? 4.0 : 1.0,
                                              child: Center(
                                                child: Padding(
                                                  padding: const EdgeInsets.all(3.0),
                                                  child: Container(
                                                    child: Padding(
                                                      padding: const EdgeInsets.all(4.0),
                                                      child: Column(
                                                        children: <Widget>[
                                                          Image.network(
                                                            category.allCategoryList[index].catThumbnail,
                                                            width: 80.0,
                                                            height: 50.0,
                                                            scale: 1.0,
                                                            loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent loadingProgress) {
                                                              if (loadingProgress == null) return child;
                                                              return Center(
                                                                child: CircularProgressIndicator(
                                                                  value: loadingProgress.expectedTotalBytes != null
                                                                      ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes
                                                                      : null,
                                                                ),
                                                              );
                                                            },
                                                          ),
                                                          Padding(
                                                            padding: const EdgeInsets.only(top: 4.0),
                                                            child: Text(
                                                              category.allCategoryList[index].catName,
                                                              textAlign: TextAlign.center,
                                                              style: TextStyle(color: Colors.black, fontSize: 10.0, fontWeight: FontWeight.w500),
                                                            ),
                                                          )
                                                        ],
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      );
                                    });
                              }
                            });
                      },
                    )

这是我的日志

I/flutter (25780): getAllCategories 
I/flutter (25780): getAllCategories 
I/flutter (25780): getAllCategories 
I/flutter (25780): getAllCategories 
I/flutter (25780): getAllCategories 
I/flutter (25780): getAllCategories 
I/flutter (25780): getAllCategories 
I/flutter (25780): getAllCategories 
I/flutter (25780): getAllCategories 
I/flutter (25780): getAllCategories 
I/flutter (25780): getAllCategories 

这种情况持续不断。

谁能帮我解决这个问题

最佳答案

查看提供的示例,您似乎在 Flutter 的 build 阶段获得了 Future。

FutureBuilder 的 documentation明确指出这将导致重复调用提供的 Future:

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.

基本上,每次 Flutter 渲染管道重建您的 widget 时,您都会初始化新的 getAllCategories() 调用。

避免这种影响的推荐方法是在 State.initStateState.didUpdateConfigState.didChangeDependencies 中初始化 Future。

关于Flutter:Future 函数正在连续调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59001341/

相关文章:

model-view-controller - MVC 作为客户端的 Nginx 配置

android - 谷歌地图 APIv2 : Failed to find provider info for com. google.settings。已设置 API key 和互联网权限

flutter - 如何检查文件类型?

flutter - 如何在触发 Dismissible 的 onDismissed() 操作之前添加操作?

dart - 如何在 Flutter 中重新加载 FileImage

Dart Future 和明确的解决、拒绝

java - 具有 CompletableFutures 且没有自定义 Executors 的代码是否仅使用等于核心数的线程数?

rust - 将数据附加到 Actix-web 中的代理响应

asp.net - "Failed to find or load the registered .Net Framework Data Provider"与 MySQL + ASP.NET

flutter - 即使使用异步,在 Flutter 中进行繁重的计算操作时 UI 也会滞后