'How to keep BLoC state on Flutter Hot Reload?
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 1:[1]
@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(...
Solution 2:[2]
Can you check if you are using a global navigatorKey in your MaterialApp ?
I removed mine and the problem was solved.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | albrnick |
| Solution 2 | Miriam |
