with是dart的关键字,意思是混入的意思,就是说可以将一个或者多个类的功能添加到自己的类无需继承这些类, 避免多重继承导致的问题。
TabBar Widget的使用
TabBar
是切换组件,它需要设置两个属性。
- controller: 控制器,后边跟的多是
TabController
组件。 - tabs:具体切换项,是一个数组,里边放的也是Tab Widget。
bottom:TabBar( controller: _controller, tabs:[ Tab(icon:Icon(Icons.directions_car)), Tab(icon:Icon(Icons.directions_transit)), Tab(icon:Icon(Icons.directions_bike)), ], )
基本页面布局
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.lightBlue ), home:KeepAlive() ); } } class KeepAlive extends StatefulWidget { @override _KeepAliveState createState() => _KeepAliveState(); } //with是关键字 解决多重继承 class _KeepAliveState extends State<KeepAlive> with SingleTickerProviderStateMixin { // 混入1个变量 TabController _controller; // 因为切换要保持状态不变 所以要重写下销毁方法和init方法 @override void initState(){ super.initState(); _controller = TabController(length: 3,vsync: this); } @override void dispose(){//重写被释放的方法,只释放TabController _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('keepAliveDemo'), bottom: TabBar( controller: _controller, tabs: <Widget>[ Tab(icon:Icon(Icons.directions)), Tab(icon:Icon(Icons.directions_bike)), Tab(icon:Icon(Icons.directions_boat)), ], ), ), body: TabBarView( controller: _controller, children: <Widget>[ MyHomePage(), MyHomePage(), MyHomePage(), ], ), ); } }
import 'package:flutter/material.dart'; class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } //混入AutomaticKeepAliveClientMixin,这是保持状态的关键 //然后重写wantKeppAlive 的值为true。 class _MyHomePageState extends State<MyHomePage> with AutomaticKeepAliveClientMixin { int _count=0; @override bool get wantKeepAlive => true; //这是一个方法 默认值为false 为ture ,就是可以有记忆功能了 void _incremenetCounter(){ setState(() { _count++; }); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('点下加1'), Text("$_count", style: Theme.of(context).textTheme.display1, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: (){ _incremenetCounter(); }, tooltip: "increment", child: Icon( Icons.add, size: 20.0, color: Colors.white, ), ), ); } }