【问题标题】:Disposing State between the pages of tabbar在 tabbar 的页面之间处理 State
【发布时间】:2019-06-09 21:45:06
【问题描述】:

我正在开发一个应用程序,其中包含一个计时器,因此它每秒更新一次状态,但是当我们更改页面时会发生一些状态错误

如果您对不再出现在小部件树中的小部件(例如,其父小部件不再在其构建中包含该小部件)调用 State 对象的 setState(),则会发生此错误。代码时可能会出现此错误 从计时器或动画回调中调用 setState()。首选的解决方案是取消计时器或停止在 dispose() 回调中收听动画。另一种解决方案是在调用 setState() 之前检查该对象的“已安装”属性,以确保该对象仍在树中。

E/flutter (5287):此错误可能表示内存泄漏,如果 setState() 被调用是因为另一个对象正在保留一个 引用此 State 对象后,它已从 树。为避免内存泄漏,请考虑中断对此的引用 dispose() 期间的对象。

我真的不知道如何以及在哪里使用 dispose() 方法

错误示例 Example

所以请帮我处理之前的小部件树,并在我们切换屏幕时重建它。

我的代码可以分为两部分。一个包含所有内容的主页和两个触发 setstate 的计时器部分。

第一部分:

import 'package:flutter/material.dart';
import '../Theme.dart' as Theme;
import '../Components/ropSayac.dart';
import '../Components/Stackvideostile.dart';

class Ropo extends StatefulWidget {
  final RopoState state = new RopoState();
  void update(bool exp) {
    state.change(exp);
  }

  RopoState createState() => state;
}

class RopoState extends State<Ropo> {
  bool videomounted, expired;
  int remday = 0, remhour = 0, remmin = 0, remsec = 0;

  void change(bool exp) {
    setState(() {
      this.expired = exp;
    });
  }

  Widget updatetimer(int rday, rhour, rmin, rsec) {
    setState(() {
      remday = rday;
      remhour = rhour;
      remmin = rmin;
      remsec = rsec;
    });
  }

  Widget sayac(BuildContext context) {
    return Container(
      color: Colors.black,
      height: 40.0,
      width: MediaQuery.of(context).size.width,
      child: new Container(
        margin: EdgeInsets.only(left: 15.0, right: 15.0),
        child: new Row(
          // mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            new Text(
              "BU HAFTAKİ RÖPORTAJA",
              style: Theme.TextStyles.ropsayacc,
            ),
            new Expanded(
              flex: 1,
              child: new Container(
                color: Colors.black,
              ),
            ),
            new Text(
              "$remday : $remhour : $remmin : $remsec",
              style: Theme.TextStyles.ropsayaccint,
            ),
          ],
        ),
      ),
    );
  }

  Widget konukyazi() {
    // BU HAFTAKİ KONUĞUMUZ
    return new Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        new Text(
          "BU HAFTAKİ",
          style: Theme.TextStyles.koseice,
        ),
        new Text(
          "KONUĞUMUZ",
          style: Theme.TextStyles.koseice,
        ),
      ],
    );
  }

  Widget konuk(String ad, var img) {
    // Yuvarlak Şeklindeki Karakter Fotoğğğğğğrafı ve Çerçevesi
    return new Container(
      child: new Column(
        children: <Widget>[
          Stack(
            alignment: Alignment.center,
            children: <Widget>[
              Container(
                width: 226.0,
                height: 226.0,
                decoration: new BoxDecoration(
                    shape: BoxShape.circle, color: Theme.Colors.pagebackground),
              ),
              Container(
                width: 215.0,
                height: 215.0,
                decoration: new BoxDecoration(
                  shape: BoxShape.circle,
                  image: DecorationImage(
                    image: new AssetImage(img),
                  ),
                ),
              ),
            ],
          ),
          new Container(
            height: 12.0,
          ),
          new Text(
            ad,
            style: Theme.TextStyles.kosebas,
          ),
        ],
      ),
    );
  }

  void initState() { 
    super.initState();
  }

  Widget updateexpired(bool expiredd) {
    setState(() {
      expired = expiredd;
    });
  }

  Widget didvideomounted() {
    if (expired == true) {
      return new Text("video");
    } else
      return new Container(
        width: 226.0,
        height: 226.0,
        decoration: new BoxDecoration(
            shape: BoxShape.circle,
            border: new Border.all(
                width: 5.0, color: Theme.Colors.roportajheroborder)),
      );
  }

  Widget rendervideoorui() {
    if (expired == false) {
      return new Column(
        children: <Widget>[
          Container(
            height: 8.0,
          ),
          konukyazi(),
          Container(
            height: 60.0,
          ),
          konuk("Ayşe Alan", "assets/ayseAlan.png"),
        ],
      );
    } else {
      return new Text("Video Geldi :D");
      // return video
    }
  }

  Widget stackvideos() {
    return new Container(
      decoration: new BoxDecoration(
        color: Theme.Colors.tabbarbackground,
        borderRadius: BorderRadius.all(Radius.circular(8.0)),
      ),
      margin: EdgeInsets.only(top: 40.0, bottom: 10.0),
      width: 358.0,
      height: 343.0,
      child: Column(
        children: <Widget>[
          Container(
            // Üstteki bar
            width: 358.0,
            height: 46.0,
            decoration: new BoxDecoration(
              color: Theme.Colors.stackvideostopbar,
              borderRadius: BorderRadius.all(Radius.circular(8.0)),
              boxShadow: <BoxShadow>[
                new BoxShadow(
                  color: Colors.black12,
                  blurRadius: 3.0,
                  offset: new Offset(0.0, 7.0),
                ),
              ],
            ),

            child: Center(
              child: new Text(
                "BENCE Bİ’ ÖNCEKİLERE DE GÖZ AT",
                style: Theme.TextStyles.stackvideotitle,
              ),
            ),
          ), //üstteki bar bitti

        ],
      ),
    );
  }



  List<String> lists = ["asdas", "adadsa"];

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Theme.Colors.pagebackground,
      child: new Stack(
        children: <Widget>[
          new Container(
            margin: EdgeInsets.only(left: 0.0, top: 37.0),
            child: Image.asset(
              "assets/k@3x.png",
             // fit: BoxFit.fill,
            ),
          ),
          new Container(
            child: new Column(
              children: <Widget>[
                RopSayac(this),

                new Expanded(
                   child: CustomScrollView(
                     slivers: <Widget>[
                       SliverToBoxAdapter(
                         child: new Column(
                           children: <Widget>[
                             rendervideoorui(),
                             new Container(height: 40.0,),
                             stackvideos(),         
                           ],
                         ),
                       ),
                     ],
                   ),
                 ),
              ],
            ),
          ),

          //new Image.asset("name"),
        ],
      ),
    );
  }
}

第二部分:

import 'package:flutter/material.dart';
import '../Pages/ropor.dart';
import '../Theme.dart' as Theme;
import 'dart:async';

class RopComponent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return null;
  }
}

class RopSayac extends StatefulWidget {
  RopoState parent;
  RopSayac(this.parent);
  _RopSayacState createState() => _RopSayacState(parent);
}

class _RopSayacState extends State<RopSayac> {
  RopoState parent;
  _RopSayacState(this.parent);
  int remday = 0, remhour = 0, remmin = 0, remsec = 0;
  bool expired = false;
  var _now = DateTime.now();
  var endpoint = DateTime.parse("2019-01-24 11:23:30");

  Timer _everySecond;
  final Ropo ropo = new Ropo();

  Widget sayac(
    BuildContext context,
  ) {
    return Container(
      color: Colors.black,
      height: 40.0,
      width: MediaQuery.of(context).size.width,
      child: new Container(
        margin: EdgeInsets.only(left: 15.0, right: 15.0),
        child: new Row(
          // mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            new Text(
              "BU HAFTAKİ RÖPORTAJA",
              style: Theme.TextStyles.ropsayacc,
            ),
            new Expanded(
              flex: 1,
              child: new Container(
                color: Colors.black,
              ),
            ),
            new Text(
              "$remday : $remhour : $remmin : $remsec",
              style: Theme.TextStyles.ropsayaccint,
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    //  RopoState bilge = new RopoState();

    // eğer videonun çıkacağı tarihten öndeysek
    //sayacı başlat
    _everySecond = Timer.periodic(Duration(seconds: 1), (Timer t) {
      if (_now.isBefore(endpoint) == true ||
          _now.difference(endpoint).inSeconds == 0) {
        //     bilge.updateexpired(false);
        expired = false;
        if (this.parent.mounted) {
          this.parent.setState(() {
            this.parent.expired = false;
          });
        }

        //    debugPrint(_now.toString());

        _now = DateTime.now();
        var remai = endpoint.difference(_now);

        ///   bilge.updatetimer(int.parse(remai.inDays.toString()), int.parse(remai.inHours.toString()) % 24, int.parse(remai.inMinutes.toString()) % 60, int.parse(remai.inSeconds.toString()) % 60);

        if (this.mounted) {
          setState(() {
            _now = DateTime.now();
            var remai = endpoint.difference(_now);
            remday = int.parse(remai.inDays.toString());
            remhour = int.parse(remai.inHours.toString()) % 24;
            remmin = int.parse(remai.inMinutes.toString()) % 60;
            remsec = int.parse(remai.inSeconds.toString()) % 60;
          });
        }
      } else {
        debugPrint("expired");
        if (this.parent.mounted) {
          this.parent.setState(() {
            this.parent.expired = true;
          });
        }

        //  bilge.updateexpired(false);
      }
    });
  }

  // defines a timer

  @override
  Widget build(BuildContext context) {
    return Container(
      child: sayac(context),
    );
  }
}

完整的错误日志:

For a more detailed help message, press "h". To detach, press "d"; to quit, press "q".
I/flutter ( 5287): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 5287): The following assertion was thrown building NotificationListener<KeepAliveNotification>:
I/flutter ( 5287): 'package:flutter/src/widgets/framework.dart': Failed assertion: line 3803 pos 12: '_state._widget ==
I/flutter ( 5287): null': is not true.
I/flutter ( 5287):
I/flutter ( 5287): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 5287): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 5287): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 5287):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 5287):
I/flutter ( 5287): When the exception was thrown, this was the stack:
I/flutter ( 5287): #2      new StatefulElement (package:flutter/src/widgets/framework.dart:3803:12)
I/flutter ( 5287): #3      StatefulWidget.createElement (package:flutter/src/widgets/framework.dart:795:38)
I/flutter ( 5287): #4      Element.inflateWidget (package:flutter/src/widgets/framework.dart:2948:40)
I/flutter ( 5287): #5      Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 5287): #6      SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4860:14)
I/flutter ( 5287): #7      Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 5287): #8      Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 5287): #9      SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4860:14)
I/flutter ( 5287): #10     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 5287): #11     Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 5287): #12     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3732:16)
I/flutter ( 5287): #13     Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 5287): #14     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3701:5)
I/flutter ( 5287): #15     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3696:5)
I/flutter ( 5287): #16     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 5287): #17     Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 5287): #18     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3732:16)
I/flutter ( 5287): #19     Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 5287): #20     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3701:5)
I/flutter ( 5287): #21     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3696:5)
I/flutter ( 5287): #22     ParentDataElement.mount (package:flutter/src/widgets/framework.dart:4047:11)
I/flutter ( 5287): #23     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 5287): #24     Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 5287): #25     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3732:16)
I/flutter ( 5287): #26     Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 5287): #27     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3701:5)
I/flutter ( 5287): #28     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3848:11)
I/flutter ( 5287): #29     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3696:5)
I/flutter ( 5287): #30     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 5287): #31     Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 5287): #32     SliverMultiBoxAdaptorElement.updateChild (package:flutter/src/widgets/sliver.dart:1028:36)
I/flutter ( 5287): #33     SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1013:20)
I/flutter ( 5287): #34     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2266:19)
I/flutter ( 5287): #35     SliverMultiBoxAdaptorElement.createChild (package:flutter/src/widgets/sliver.dart:1006:11)
I/flutter ( 5287): #36     RenderSliverMultiBoxAdaptor._createOrObtainChild.<anonymous closure> (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:274:23)
I/flutter ( 5287): #37     RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:1730:58)
I/flutter ( 5287): #38     PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:799:15)
I/flutter ( 5287): #39     RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:1730:13)
I/flutter ( 5287): #40     RenderSliverMultiBoxAdaptor._createOrObtainChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:263:5)
I/flutter ( 5287): #41     RenderSliverMultiBoxAdaptor.insertAndLayoutLeadingChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:372:5)
I/flutter ( 5287): #42     RenderSliverFixedExtentBoxAdaptor.performLayout (package:flutter/src/rendering/sliver_fixed_extent_list.dart:184:31)
I/flutter ( 5287): #43     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 5287): #44     RenderViewportBase.layoutChildSequence (package:flutter/src/rendering/viewport.dart:405:13)
I/flutter ( 5287): #45     RenderViewport._attemptLayout (package:flutter/src/rendering/viewport.dart:1316:12)
I/flutter ( 5287): #46     RenderViewport.performLayout (package:flutter/src/rendering/viewport.dart:1234:20)
I/flutter ( 5287): #47     RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1509:7)
I/flutter ( 5287): #48     PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:768:18)
I/flutter ( 5287): #49     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:281:19)
I/flutter ( 5287): #50     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:677:13)
I/flutter ( 5287): #51     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 5287): #52     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 5287): #53     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 5287): #54     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
I/flutter ( 5287): #55     _invoke (dart:ui/hooks.dart:154:13)
I/flutter ( 5287): #56     _drawFrame (dart:ui/hooks.dart:143:3)
I/flutter ( 5287): (elided 2 frames from class _AssertionError)
I/flutter ( 5287): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 235 pos 16: 'indexOf(child) > index': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 235 pos 16: 'indexOf(child) > index': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 2270 pos 20: '_debugCurrentBuildTarget == context': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 461 pos 12: 'child.hasSize': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 574 pos 16: 'indexOf(child) == index': is not true.
I/chatty  ( 5287): uid=10086(com.example.aurorav10) 1.ui identical 2 lines
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 574 pos 16: 'indexOf(child) == index': is not true.
E/flutter ( 5287): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 5287): setState() called after dispose(): RopoState#2b3f4(lifecycle state: defunct)
E/flutter ( 5287): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code
calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter ( 5287): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter ( 5287): #0      State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1103:9)
E/flutter ( 5287): #1      State.setState (package:flutter/src/widgets/framework.dart:1129:6)
E/flutter ( 5287): #2      _RopSayacState.initState.<anonymous closure> (package:aurorav10/Components/ropSayac.dart:111:23)
E/flutter ( 5287): #3      _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
E/flutter ( 5287): #4      _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
E/flutter ( 5287): #5      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1008 pos 14: 'insertFirst || _childElements[index-1] != null': is not true.
I/chatty  ( 5287): uid=10086(com.example.aurorav10) 1.ui identical 3 lines
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1008 pos 14: 'insertFirst || _childElements[index-1] != null': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1053 pos 14: '_childElements.containsKey(index)': is not true.
I/chatty  ( 5287): uid=10086(com.example.aurorav10) 1.ui identical 43 lines
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1053 pos 14: '_childElements.containsKey(index)': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1008 pos 14: 'insertFirst || _childElements[index-1] != null': is not true.
I/chatty  ( 5287): uid=10086(com.example.aurorav10) 1.ui identical 7 lines
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1008 pos 14: 'insertFirst || _childElements[index-1] != null': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 574 pos 16: 'indexOf(child) == index': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 235 pos 16: 'indexOf(child) > index': is not true.
I/chatty  ( 5287): uid=10086(com.example.aurorav10) 1.ui identical 1 line
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 235 pos 16: 'indexOf(child) > index': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 2270 pos 20: '_debugCurrentBuildTarget == context': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 461 pos 12: 'child.hasSize': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 574 pos 16: 'indexOf(child) == index': is not true.
I/chatty  ( 5287): uid=10086(com.example.aurorav10) 1.ui identical 4 lines
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 574 pos 16: 'indexOf(child) == index': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1053 pos 14: '_childElements.containsKey(index)': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 574 pos 16: 'indexOf(child) == index': is not true.
I/chatty  ( 5287): uid=10086(com.example.aurorav10) 1.ui identical 6 lines
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 574 pos 16: 'indexOf(child) == index': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1053 pos 14: '_childElements.containsKey(index)': is not true.
I/chatty  ( 5287): uid=10086(com.example.aurorav10) 1.ui identical 9 lines
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1053 pos 14: '_childElements.containsKey(index)': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1053 pos 14: '_childElements.containsKey(index)': is not true.
I/chatty  ( 5287): uid=10086(com.example.aurorav10) 1.ui identical 58 lines
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1053 pos 14: '_childElements.containsKey(index)': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 574 pos 16: 'indexOf(child) == index': is not true.
I/chatty  ( 5287): uid=10086(com.example.aurorav10) 1.ui identical 6 lines
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 574 pos 16: 'indexOf(child) == index': is not true.
I/flutter ( 5287): Another exception was thrown: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 1053 pos 14: '_childElements.containsKey(index)': is not true.

谢谢

【问题讨论】:

    标签: dart flutter stateful


    【解决方案1】:

    首先,请在发布问题时将代码精简到绝对必要的程度。那里有很多代码需要解析(特别是因为它不是全英文的)。至少,清理你的 cmets 等......

    但手头的问题是,您在 _RopSayacState 的 initState() 函数中创建了一个计时器,但从不停止它。正如您在问题中包含的错误所解释的那样,这将导致问题,因为当小部件不再在视图中时,它会从小部件树中删除,因此在其上调用 setState 会导致错误。

    要解决此问题,您只需在删除小部件时取消计时器即可。最简单的方法是覆盖 _RopSayacState 中的 dispose 方法。应该是这样的。

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

    【讨论】:

    • 是的,对不起,我在干净的编码方面遇到了严重的问题。一点建议会很宝贵。顺便说一句,它解决了处置错误,但是当我更改页面并返回我的计时器页面时,我仍然遇到同样的错误。我正在发布错误日志作为答案,请查看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    相关资源
    最近更新 更多