20个Flutter实例视频教程-第09节: 保持页面状态-2
视频地址:https://www.bilibili.com/video/av39709290/?p=9
博客地址:https://jspang.com/post/flutterDemo.html#toc-e3a
新建keep_alive_demo.dart.
里面新建类 MyHomePage是一个动态的widget
with只能引入混入的mixin的。AutomaticKeepAliveClientMixin
声明一个计数器:并重写wantKeepAlive
再声明一个内部的方法。点击按钮增加我们的计数器
然后写我们的build
然后再写我们浮动的按钮。用floatingActionButton
main.dart引入页面
预览效果:
从第二个切回到一个tab。里面的数字不变,状态保持了
最终代码:
import 'package:flutter/material.dart'; import 'keep_alive_demo.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: KeepAliveDemo() ); } } class KeepAliveDemo extends StatefulWidget { @override _KeepAliveDemoState createState() => _KeepAliveDemoState(); } class _KeepAliveDemoState extends State<KeepAliveDemo> with SingleTickerProviderStateMixin { TabController _controller; @override void initState() { super.initState(); _controller=TabController(length: 3,vsync:this); } @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_transit),), Tab(icon: Icon(Icons.directions_bike),), ] ), ), body: TabBarView( controller: _controller, children: <Widget>[ MyHomePage(), MyHomePage(), MyHomePage(), ], ), ); } }
import 'package:flutter/material.dart'; class MyHomePage extends StatefulWidget { @override _MyHomePageState 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: <Widget>[ Text('点一次增加一个数字'), Text( '$_counter', style: Theme.of(context).textTheme.display1, ) ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: '增加', child: Icon(Icons.add), ), ); } }