Issue
I'm an android developer and I want to switch to flutter. I love the hot reload feature that allows for faster development time. The only thing that prevents me from switching so far is that flutter lacks the option to save the app state when the activity is killed. In native android the option is provided for free (onSaveInstanceState(Bundle savedInstanceState)
). So my question is, how can I implement the same feature in Flutter?
Solution
Beginning with Flutter 1.22 (which is now in stable), you can make use of RestorationMixin
. Here's a full example:
void main() {
runApp(
RootRestorationScope(
restorationId: 'root',
child: MaterialApp(home: HomePage()),
),
);
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with RestorationMixin {
final RestorableInt _counter = RestorableInt(0);
@override
String get restorationId => 'HomePage';
@override
void restoreState(RestorationBucket oldBucket, bool initialRestore) {
registerForRestoration(_counter, 'counter');
}
@override
void dispose() {
_counter.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
child: Text('${_counter.value}'),
onPressed: () => setState(() => ++_counter.value),
),
),
);
}
}
How to test:
- Go to your device Settings - Developer Options and turn on
Don't keep activities
.
Now run the app on your Android device, tap the Counters button and hit the home button to force Android to exit your app.
Open the app again and you should see the
counter
value persist.
Answered By - CopsOnRoad
Answer Checked By - Terry (JavaFixing Volunteer)