在Flutter 框架中,当用户想要在页面切换时保持页面活动状态,即用户导航离开后返回时,希望看到的是离开时的界面状态而不是重新构建的界面,或者不希望用户返回时重新请求数据,这时候 AutomaticKeepAliveClientMixin 就派上用场了。
具体用法如下:
class MyPage extends StatefulWidget {
@override
_MyPageState createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> with AutomaticKeepAliveClientMixin<MyPage> {
@override
Widget build(BuildContext context) {
super.build(context); // 确保 mixin 的行为得以应用
return Scaffold(
appBar: AppBar(title: Text('My Page')),
body: ListView.builder(
itemCount: 20,
itemBuilder: (context, index) {
return ListTile(
title: Text('Item $index'),
);
},
),
);
}
@override
bool get wantKeepAlive => true;
}
这样就实现了状态的保持