如何在 Flutter Hot Reload 上保持 BLoC 状态?

How to keep BLoC state on Flutter Hot Reload?

我喜欢 Flutter 热重载,但发现我的 BLoC 中的状态没有保留。每次我进行热重载时它都会重置。

有没有办法保存该状态,使其在热重载后仍然存在? (我可以接听的电话还是什么?)

感谢您的宝贵时间!

@RémiRousselet 说得对!我在有状态小部件之外保持状态!为了清楚起见,这里是之前和之后的代码。 (MaterialApp home: 参数,_MyHomePageState.build才是真正变化的地方)

错误代码:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: BlocProvider<PandemicBloc>(
          bloc: PandemicBloc(), child: MyHomePage(title: 'Pandemic Tracker')),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final PandemicBloc pandemicBloc = BlocProvider.of<PandemicBloc>(context);
  int _currentTab = 0;

  Widget build(BuildContext context) {
    return DefaultTabController(...

好的代码:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(title: 'Pandemic Tracker'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _currentTab = 0;
  final _pandemicBloc = PandemicBloc();

  Widget build(BuildContext context) {
    return BlocProvider<PandemicBloc>(
      bloc: _pandemicBloc,
      child: DefaultTabController(...

你能检查一下你的 MaterialApp 中是否使用了全局 navigatorKey 吗?

我删除了我的,问题就解决了。