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

时间:2019-03-13 18:04:14

标签: flutter hot-reload bloc

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

有没有一种方法可以保存该状态,使其在热重载后仍然存在? (我可以挂断电话吗?)

感谢您的时间!

1 个答案:

答案 0 :(得分:0)

@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(...