1

我有一个图像路径列表,我正在使用List.generate显示图像的方法和一个十字图标从列表中删除图像。对每个图像调用上传方法,当我从列表中删除图像时,该方法仍会继续运行,直到图像被上传。我期望的行为是当我从列表中删除图像时,该方法也应该停止运行。我正在使用未来的构建器在上传图像时显示圆形进度条和错误图标。

当我从列表中删除小部件时,我应该怎么做才能确保与当前小部件关联的未来方法也停止?

这是我创建列表的代码

           List.generate(
            files.length,
            (index) {
              var image = files[index];             
              return Container(
                height: itemSize,
                width: itemSize,
                child: Stack(
                  children: <Widget>[
                    Container(
                       getImagePreview(image, itemSize)                          
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        uploadHandler(image, field),
                          InkWell(
                            onTap: () => removeFileAtIndex(index, field),
                            child: Container(
                              margin: EdgeInsets.all(3),
                              decoration: BoxDecoration(
                                color: Colors.grey.withOpacity(.7),
                                shape: BoxShape.circle,
                              ),
                              alignment: Alignment.center,
                              height: 22,
                              width: 22,
                              child: Icon(Icons.close, size: 18, color: Colors.white),
                            ),
                          ),
                      ],
                    ),
                  ],
                ),
              );
            },
          )

这是上传处理程序方法。

Widget uploadHandler(file, field) {
    return FutureBuilder(
      future: upload(file),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.data.statusCode == 201) {            
            return doneUpload();
          } else {
            logger.d(snapshot.error);
            return error();
          }
        } else {
          return uploading();
        }
      },
    );
  }
4

1 回答 1

0

小部件的生命周期不附加到小部件调用的异步函数。

您可以检查mounted变量以检查小部件是否仍从您的异步函数安装。

于 2020-10-27T05:09:58.440 回答