The widget on which setState() or markNeedsBuild() was called exception

一、异常信息

I/flutter (30504): [E]: message: {error: setState() or markNeedsBuild() called during build.
I/flutter (30504): This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
I/flutter (30504): The widget on which setState() or markNeedsBuild() was called was:
I/flutter (30504):   Overlay-[LabeledGlobalKey<OverlayState>#b5023]
I/flutter (30504): The widget which was currently being built when the offending call was made was:
I/flutter (30504):   NotificationListener<KeepAliveNotification>, stackTrace: #0      Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:4424:11)
I/flutter (30504): #1      Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:4439:6)
I/flutter (30504): #2      State.setState (package:flutter/s
I/flutter (30504): [E]: message: {error: '

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个报错通常是由于在组件被销毁后仍然调用了 `setState()` 方法导致的。报错信息建议在 `dispose()` 回调中取消定时器或停止监听动画,或者在调用 `setState()` 之前检查组件的 `mounted` 属性以确保组件仍然在树中。 为了解决这个问题,你可以按照以下步骤进行操作: 1. 在组件的 `dispose()` 方法中,确保取消所有定时器、动画或其他回调函数的监听。这可以通过调用相应的取消方法来完成,例如 `timer.cancel()`、`animationController.dispose()` 等。 2. 在调用 `setState()` 方法之前,检查组件的 `mounted` 属性。你可以使用 `mounted` 属性来判断组件是否仍然在树中。如果组件已经被销毁,可以避免调用 `setState()`。 下面是一个示例代码: ```dart import 'package:flutter/material.dart'; class MyWidget extends StatefulWidget { @override _MyWidgetState createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { Timer _timer; AnimationController _animationController; bool _isDisposed = false; @override void dispose() { _isDisposed = true; _timer.cancel(); _animationController.dispose(); super.dispose(); } void _myMethod() { if (_isDisposed) { return; } if (mounted) { setState(() { // 在这里更新组件状态 }); } } @override Widget build(BuildContext context) { return Container( // 组件的 UI 构建 ); } } ``` 通过在 `dispose()` 方法中取消定时器、动画等,并在调用 `setState()` 之前检查组件的 `mounted` 属性,你可以避免这个报错。确保及时清理资源是避免内存泄漏的重要步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值