How to keep BLoC state on Flutter Hot Reload?

Issue

I love the Flutter hot reload, but find the state in my BLoC isn’t keep. It gets reset every time I do a hot reload.

Is there a way to save that state so it persists after a hot reload? (a call I can hook into or something?)

Thanks for your time!

Solution

@RĂ©miRousselet was spot on! I was keeping state outside of the stateful widget! Just for clarity, here is the code before and after. (The MaterialApp home: parameter, and _MyHomePageState.build are where the real changes are)

Bad Code:

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

Good Code:

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

Answered By – albrnick

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.