我正在使用这个插件 https://pub.dev/packages/last_state ,但是当我更新到 flutter 1.22 时,出现了一个新功能 RootRestorationScope
似乎可以取代那个外部插件,但是在测试它并遵循一些教程( tuto1 , tuto2 )之后我注意到它恢复状态但不恢复路由!我错过了什么吗?
有一个例子:
import 'package:flutter/material.dart';
void main() => runApp(
RootRestorationScope( // Register a restoration scope for the entire app!
restorationId: 'root',
child: MyApp(),
),
);
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DummyPage(),
);
}
}
class DummyPage extends StatelessWidget {
static const route = "/intermediate";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Another page'),
),
body: RaisedButton(
child: Text("Onwards"),
onPressed: () {
Navigator.of(context, rootNavigator: false).push(
MaterialPageRoute<bool>(
fullscreenDialog: true,
builder: (BuildContext context) => HomePage(),
),
);
},
),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
// Our state should be mixed-in with RestorationMixin
class _HomePageState extends State<HomePage> with RestorationMixin {
// For each state, we need to use a restorable property
final RestorableInt _index = RestorableInt(0);
@override
Widget build(BuildContext context) {
return RestorationScope(
restorationId: 'tess',
child: Scaffold(
body: Center(child: Text('Index is ${_index.value}')),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _index.value,
onTap: (i) => setState(() => _index.value = i),
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home'
),
BottomNavigationBarItem(
icon: Icon(Icons.notifications),
label: 'Notifications'
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings'
),
],
),
),
);
}
@override
// The restoration bucket id for this page,
// let's give it the name of our page!
String get restorationId => 'home_page';
@override
void restoreState(RestorationBucket oldBucket, bool initialRestore) {
// Register our property to be saved every time it changes,
// and to be restored every time our app is killed by the OS!
registerForRestoration(_index, 'nav_bar_index');
}
}
最佳答案
使用 restorablePush
而不是 push
并为每条路线分配一个 restorationId
Routes added with the classic imperative API (push, pushNamed, and friends) can never restore their state. A Route added with the restorable imperative API (restorablePush, restorablePushNamed, and all other imperative methods with "restorable" in their name) restores its state if all routes below it up to and including the first Page-based route below it are restored. If there is no Page-based route below it, it only restores its state if all routes below it restore theirs.
https://api.flutter.dev/flutter/widgets/Navigator-class.html
关于Flutter RootRestorationScope 不恢复最后一个根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65142002/