【问题标题】:Flutter extended_image: setState() or markNeedsBuild() called during buildFlutter extended_image:在构建期间调用了 setState() 或 markNeedsBuild()
【发布时间】:2021-04-19 00:20:15
【问题描述】:

我正在使用包extended_image 从网络加载图像并在加载或错误时显示闪光。

当我尝试在 loadStateChanged 中调用 setState 时,我收到此错误 setState() or markNeedsBuild() called during build

事实上,我有两个小部件,一个 VideoThumbnail 负责从网络加载缩略图,另一个 VideoDesc 应该显示缩略图描述。

但我希望当图片加载失败或加载时间较长时,描述会显示闪光。

我在 VideoThumbnail 小部件上创建了两个状态变量,它们应该传递给 VideoDesc 小部件

videoLoading = true;
videoError = false;

这是我在 repo 示例之后的代码:

视频缩略图状态

class _VideoThumbnailState extends State<VideoThumbnail>
    with SingleTickerProviderStateMixin {
  bool videoLoading;
  bool videoError;

  AnimationController _controller;

  @override
  void initState() {
    videoLoading = true;
    videoError = false;

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    );
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      print("Build Process Complete");
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(4.0),
            child: ExtendedImage.network(
              widget.videoUrl,
              width: widget.width,
              height: (widget.width) * 3 / 4,
              loadStateChanged: (ExtendedImageState state) {
                switch (state.extendedImageLoadState) {
                  case LoadState.loading:
                    _controller.reset();

                    setState(() {
                      videoError = false;
                      videoLoading = true;
                    });

                    return Shimmer.fromColors(
                      child: Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4.0),
                        ),
                      ),
                      baseColor: Colors.black12,
                      highlightColor: Colors.white24,
                    );
                    break;

                  case LoadState.completed:
                    _controller.forward();

                    setState(() {
                      videoError = false;
                      videoLoading = false;
                    });

                    return FadeTransition(
                      opacity: _controller,
                      child: ExtendedRawImage(
                        image: state.extendedImageInfo?.image,
                        width: widget.width,
                        height: (widget.width) * 3 / 4,
                      ),
                    );

                    break;

                  case LoadState.failed:
                    _controller.reset();
                    state.imageProvider.evict();

                    setState(() {
                      videoError = true;
                      videoLoading = false;
                    });

                    return Container(
                      width: widget.width,
                      height: (widget.width) * 3 / 4,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage("assets/img/not-found.png"),
                          fit: BoxFit.fill,
                        ),
                      ),
                    );

                    break;

                  default:
                    return Container();
                }
              },
            ),
          ),
          VideoDesc(
            desc: widget.desc,
            videoError: videoError,
            videoLoading: videoLoading,
          )
        ],
      ),
    );
  }
}

视频小部件

class VideoDesc extends StatelessWidget {
  final String desc;
  final bool videoLoading;
  final bool videoError;

  const VideoDesc({
    Key key,
    @required this.desc,
    this.videoLoading = true,
    this.videoError = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: videoError || videoLoading
          ? Shimmer.fromColors(
              baseColor: Colors.grey[700],
              highlightColor: Colors.white24,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  SizedBox(height: 12.0),
                  Container(
                    width: double.infinity,
                    height: 8.0,
                    decoration: BoxDecoration(
                      color: Colors.grey[900],
                      borderRadius: BorderRadius.circular(2.0),
                    ),
                  ),
                  SizedBox(height: 12.0),
                  Container(
                    width: 80.0,
                    height: 8.0,
                    decoration: BoxDecoration(
                      color: Colors.grey[900],
                      borderRadius: BorderRadius.circular(2.0),
                    ),
                  ),
                ],
              ),
            )
          : Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(height: 12.0),
                Text(
                  desc,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 11.0,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
                SizedBox(height: 5.0),
                Text(
                  "361,143,203 views",
                  style: TextStyle(
                    color: Colors.white54,
                    fontSize: 12.0,
                  ),
                ),
              ],
            ),
    );
  }
}

谁能帮我解决这个问题?或者,如果有更好的方法来获取 extendedImageLoadState 值并将其传递给另一个小部件,而无需在 loadStateChanged 中调用 setState

【问题讨论】:

    标签: flutter setstate dart-pub statefulwidget


    【解决方案1】:

    在构建过程中你不能调用setState

    如果你真的需要,你可以使用:

    WidgetsBinding.instance.addPostFrameCallback(() => setState((){}));
    

    但是,请记住,在您的 switch-case 上添加此内容会安排一个您不想要的无限循环的重建。

    我建议你重新构建你的 UI 逻辑,或者至少让它有条件:

    if(!videoLoading) {
     WidgetsBinding.instance.addPostFrameCallback(() => setState((){
            videoError = false;
            videoLoading = true;  
    }));
    }
     
    

    【讨论】:

    • Miguel Ruivo,感谢您的快速回复,我会尝试您的建议。稍后再联系您
    猜你喜欢
    • 2019-02-19
    • 2020-12-12
    • 2020-12-28
    • 2021-01-06
    • 2021-05-31
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多