Search code examples
flutterflutter-hooks

How to use Flutter State Restoration with HookWidget


I want to use Flutter State Restoration in my Flutter app. I want to save/restore some data and on internet all articles suggest to use RestorationMixin for this. How can I use RestorationMixin with HookWidget ? enter image description here


Solution

  • Well I have the answer now, it can be done using RestorationBucket directly. Below is the complete source code.

    import 'package:flutter/material.dart';
    import 'package:flutter_hooks/flutter_hooks.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          restorationScopeId: 'root',
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends HookWidget {
      const MyHomePage({super.key});
    
      static const counterKey = 'counter-key';
    
      @override
      Widget build(BuildContext context) {
        final refreshCounter = useState(0);
        final restorationBucket = RestorationScope.of(context);
        final counter = restorationBucket?.read<int>(counterKey) ?? 0;
    
        return Scaffold(
          appBar: AppBar(
            title: const Text('Restore State Demo'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                const Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$counter',
                  style: Theme.of(context).textTheme.headline4,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              restorationBucket?.write(counterKey, counter + 1);
              refreshCounter.value++;
            },
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ),
        );
      }
    }
    

    We can also use this plugin but I am not sure if it will be maintained regularly.