简单叙述原理:每一个Tab页 with AutomaticKeepAliveClientMixin, 就是将页面存入内存中,慎用。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: TabBarDemo(),
);
}
}
class TabBarDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
title: Text('Tabs Demo'),
),
body: TabBarView(
children: [
Page1(),
Page2(),
Page3(),
],
),
),
),
);
}
}
class Page1 extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _Page1State();
}
}
class _Page1State extends State<Page1> with AutomaticKeepAliveClientMixin {
@override
void initState() {
super.initState();
print("Page 1 init");
}
@override
Widget build(BuildContext context) {
super.build(context);
return Text("Page 1");
}
@override
bool get wantKeepAlive => true;
}
class Page2 extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _Page2State();
}
}
class _Page2State extends State<Page2> with AutomaticKeepAliveClientMixin {
@override
void initState() {
super.initState();
print("Page 2 init");
}
@override
Widget build(BuildContext context) {
super.build(context);
return Text("Page 2");
}
@override
bool get wantKeepAlive => true;
}
class Page3 extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _Page3State();
}
}
class _Page3State extends State<Page3> with AutomaticKeepAliveClientMixin {
@override
void initState() {
super.initState();
print("Page 3 init");
}
@override
Widget build(BuildContext context) {
super.build(context);
return Text("Page 3");
}
@override
bool get wantKeepAlive => true;
}