调用setState()在一个不再出现在小部件树中的小部件的State对象上。

huangapple go评论66阅读模式
英文:

Calling setState() on a State object for a widget that no longer appears in the widget tree

问题

我正在创建一个Flutter应用程序,在其中一个类中出现了异常:

未处理的异常:在dispose()之后调用了setState():_DetalleEmailEntranteScreenState#51a48(生命周期状态:不可用,未挂载)

这里是它的initState部分:

@override
void initState() {
  // TODO: implement initState
  super.initState();
  checkSiAdmin();
  checkSiComercial();

  getEmailUsuarioActual();
  //  getNombreUsuarioActual();
  //  getApellidosUsuarioActual();
  getImagenUsuarioActual();
  getTelUsuarioActual();
  getIdUsuarioActual();
  getMiGrupoAdministrador();
  obtenerAdjuntosEmails();
  obtenerDestinatariosEmails();
  obtenerBodyEmails();

  if (mounted) {
    setState(() {
      timer = Timer.periodic(Duration(seconds: 2), (Timer t) => refresh());
    });

  }
}

这里是dispose部分:

@override
void dispose() {
  timer.cancel();
  super.dispose();
}

我不明白问题出在哪里?

英文:

I am creating a Flutter app, in one of its classes I am getting the exception:

Unhandled Exception: setState() called after dispose(): _DetalleEmailEntranteScreenState#51a48(lifecycle state: defunct, not mounted)

Here yoy have the initState part of it:

 @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkSiAdmin();
    checkSiComercial();

    getEmailUsuarioActual();
    //  getNombreUsuarioActual();
    //  getApellidosUsuarioActual();
    getImagenUsuarioActual();
    getTelUsuarioActual();
    getIdUsuarioActual();
    getMiGrupoAdministrador();
    obtenerAdjuntosEmails();
    obtenerDestinatariosEmails();
    obtenerBodyEmails();


    if (mounted) {
      setState(() {
        timer = Timer.periodic(Duration(seconds: 2), (Timer t) => refresh());
      });

    }

  }

And here the dispose part of it:

 @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

I don´t understand where is the issue?

答案1

得分: 1

> 移除 setState 并尝试使用以下代码:

    if (mounted) {
          timer = Timer.periodic(Duration(seconds: 2), (Timer t) => refresh());
        }
英文:

> Remove setState and try this:

if (mounted) {
      timer = Timer.periodic(Duration(seconds: 2), (Timer t) => refresh());
    }

huangapple
  • 本文由 发表于 2023年7月24日 16:46:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76752781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定