【问题标题】:Statefull widget state is rebuilt after back pressed有状态的小部件状态在后按后重建
【发布时间】:2020-04-25 19:57:47
【问题描述】:

我有一个奇怪的问题: 我有这样的 StatefullWidget

class ActionDetailView extends StatefulWidget {
  static const routeName = '/actionDetails';

  @override
  _ActionDetailViewState createState() {
    print("Create state");
    return _ActionDetailViewState();
  }
}

class _ActionDetailViewState extends State<ActionDetailView>
  with WidgetsBindingObserver {
  ActionDetailBloc _bloc = ActionDetailBloc();

  _ActionDetailViewState() {
    print("ActionDetailViewState constructed");
  }

  @override
  void didChangeDependencies() {
      print("DidChangeDependencicse");
      final String actionUID = ModalRoute.of(context).settings.arguments;
    _bloc.init(actionUID);
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(...)
  }

我的日志如下所示:

============= Enter to view first time =======
2020-01-08 09:53:36.760 5960-5987/ I/flutter: View action //pushed route from another place in code
2020-01-08 09:53:36.808 5960-5987/ I/flutter: Create state //constructor of State is called
2020-01-08 09:53:36.810 5960-5987/ I/flutter: ActionDetailViewState constructed //confirmation of above
2020-01-08 09:53:36.811 5960-5987/ I/flutter: DidChangeDependencicse
2020-01-08 09:53:36.812 5960-5987/ I/flutter: init actionDetailBloc //bloc init method for fill streams
2020-01-08 09:53:36.864 5960-5987/ I/flutter: LoadingUsers //loading state
2020-01-08 09:53:38.253 5960-5987/ I/flutter: pushing to stream
2020-01-08 09:53:38.276 5960-5987/ I/flutter: ReceivedList //data received
=============== Back pressed ====
2020-01-08 09:53:40.870 5960-5987/ I/flutter: DidChangeDependencicse //suddenly it is rebuilt despite not visible
2020-01-08 09:53:40.870 5960-5987/ I/flutter: init actionDetailBloc
2020-01-08 09:53:40.884 5960-5987/ I/flutter: ReceivedList
2020-01-08 09:53:42.160 5960-5987/ I/flutter: pushing to stream

所以从日志看,小部件的状态似乎在没有收到任何新路由的情况下被重建,因此它造成了麻烦,因为调用了 dispose() 并且 BLoC 中的所有流都已关闭。 StreamBuilder 根据流数据和主体中的多个 Widget 或 StatelessWidget 以两种状态之一返回 Scaffold。无处被称为 setState()。 Widget 由 Navigator 通过 pushRouteNamed() 打开。

我的问题是:是什么导致了这种奇怪的行为以及如何防止它?想法是每次通过推送路由创建Widget时创建bloc(它包含上下文数据,所以单例不会好)

【问题讨论】:

    标签: flutter statefulwidget


    【解决方案1】:

    是的,目前他们正在修复它。这里是颤动 issue link

    链接中还提到了一种解决方法。

    副本: How to deal with unwanted widget build?

    【讨论】:

      猜你喜欢
      • 2020-04-17
      • 2021-06-24
      • 2020-03-18
      • 2018-10-10
      • 2021-02-16
      • 2021-12-15
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多