Я хочу использовать восстановление состояния Flutter в своем приложении Flutter. Я хочу сохранить/восстановить некоторые данные, и в Интернете все статьи предлагают использовать для этого RestorationMixin. Как я могу использовать RestorationMixin с HookWidget?





Теперь у меня есть ответ, это можно сделать напрямую с помощью RestorationBucket. Ниже приведен полный исходный код.
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),
),
);
}
}
Мы также можем использовать этот плагин, но я не уверен, что он будет поддерживаться регулярно.
В случае, если MaterialApp нужны восстановленные данные, мы можем обернуть MaterialApp с помощью RootRestorationScope и установить там restoreId вместо restoreScopeId MaterialApp.