Flutter 组件通信时遇到的问题

Flutter 组件通信时遇到的问题


在fluttet的使用中组件通信是必不可少的…吧?:最近用组件通信时遇到了这样一个问题:
在退出当前页面后再次进入通过

[ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter (32275): setState() called after dispose(): _BaseHistiryChartState#88545(lifecycle state: defunct, not mounted)
E/flutter (32275): 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.

代码如下

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.type=widget.type;
    this.time=widget.time;
    //数据监控
    historyEventBus.on<HistoryEventBusType>().listen((HistoryEventBusType data)=>
        showType(data.type)
    );
    historyEventBus.on<HistoryEventBusData>().listen((HistoryEventBusData data)=>
        showData(data.data)
    );
    subscriptionType.resume();   //  开启
    subscriptionData.resume();
  }

原因是因为使用了组件通信的监控,但是关闭当前页面时监控并不会自动销毁.

解决方法
在state销毁时调用控制器StreamSubscription
代码如下:

//EvenBus控制器
  StreamSubscription subscriptionType =null;
  StreamSubscription subscriptionData =null;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    subscriptionType.cancel();   //  取消
    subscriptionData.cancel();
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.type=widget.type;
    this.time=widget.time;
    //数据监控
    subscriptionType=historyEventBus.on<HistoryEventBusType>().listen((HistoryEventBusType data)=>
        showType(data.type)
    );
    subscriptionData=historyEventBus.on<HistoryEventBusData>().listen((HistoryEventBusData data)=>
        showData(data.data)
    );
    subscriptionType.resume();   //  开启
    subscriptionData.resume();
  }

描述的有什么错误还请各位大佬留言

你可能感兴趣的:(flutter)