1,在State类中混入AutomaticKeepAliveClientMixin这个类
2,重写AutomaticKeepAliveClientMixin中的wantKeepAlive方法
3,在build中调用父类的build方法
main.dart
import 'package:flutter/material.dart';
import 'keep_alive_demo.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(primarySwatch: Colors.green),
home: KeepAliveDemo());
}
}
class KeepAliveDemo extends StatefulWidget {
const KeepAliveDemo({Key? key}) : super(key: key);
@override
State<KeepAliveDemo> createState() => _KeepAliveDemoState();
}
/*
with是dart的关键字,意思是混入的意思,
就是说可以将一个或者多个类的功能添加到自己的类无需继承这些类,
避免多重继承导致的问题。
SingleTickerProviderStateMixin 主要是我们初始化TabController时,
需要用到vsync ,垂直属性,然后传递this
*/
/**TabController
* 使用 TabController 更有利于事件的监听,便于控制相关内容。
* 实现底部tab切换
*/
class _KeepAliveDemoState extends State<KeepAliveDemo>
with SingleTickerProviderStateMixin {
late TabController _controller;
@override
void initState() {
_controller = TabController(length: 3, vsync: this);
super.initState();
}
@override //重写销毁方法
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Keep Alive Demo'),
bottom: TabBar(
controller: _controller,
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_bike)),
Tab(icon: Icon(Icons.directions_boat)),
],
),
),
body: TabBarView(
controller: _controller,
children: <Widget>[
MyHomePage(),
MyHomePage(),
MyHomePage(),
],
),
);
}
}
keep_alive_demo.dart
import 'package:flutter/material.dart';
import 'package:flutter_keepalive/main.dart';
void main() => (MyApp());
class MyHomePage extends StatefulWidget {
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with AutomaticKeepAliveClientMixin {
int _counter = 0;
@override
bool get wantKeepAlive => true;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('点一次增加一个数字'),
Text(
'$_counter',
style: Theme.of(context).textTheme.displayMedium,
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}