我在绘制进度指示器时遇到问题

I'm having trouble drawing the progress indicator

我正在实现文件上传。我想用CircularProgressIndicator显示上传进度。

FileUploadController 的 uploadFile() 函数 class 将文件上传到服务器并告知上传进度的百分比。并且每帧调用'NotifyListeners()'以通知上传进度。

我试图用这些信息绘制一个 CircularProgressIndicator,但是我得到了一个错误。 “setstate() 或 markneedsbuild() 在构建期间调用。

  @override
  Widget build(BuildContext context) {
    var uploadController = Provider.of<FileUploadController>(context);
    uploadController.uploadFile(userFiles, context);//upload files and update uploadPercentage
    return ListTile(
      leading: Stack(
        children: [
          CircularProgressIndicator(
            value: userFiles.uploadPercentage,
            strokeWidth: userFiles.uploadPercentage == 1 ? 0 : 1,
          ),
          Positioned(
            right: 3,
            left: 3,
            top: 3,
            bottom: 3,
            child: CircleAvatar(
              backgroundColor: Colors.white,
              backgroundImage:
                  AssetImage('assets/images/fileTypeLogos/pdf.png'),
            ),
          ),
        ],
      ),
      title: Text(widget.fileName),
      trailing: IconButton(
        icon: Icon(Icons.close),
        onPressed: () => widget.removeWhenCloseButtonTap(widget.fileName),
      ),
    );
  }

我认为问题在于在 build() 中调用 notifyListeners()(uploadFile 函数调用它)。我该如何解决?

是的,这可能就是问题所在。您可能希望在 initState() 中调用 uploadFile() :

FileUploadController uploadController(BuildContext context) => Provider.of<FileUploadController>(context);

@override
void initState() {
  super.initState();
  uploadController(context).uploadFile(userFiles, context);
}

如果您使用的是无状态小部件,请将其转换为有状态小部件。