import 'package:flutter/material.dart'; class LifecycleAppPage extends StatefulWidget { @override State<StatefulWidget> createState() { return new _LifecycleAppPageState('构造函数'); } } class _LifecycleAppPageState extends State<LifecycleAppPage> with WidgetsBindingObserver { String str; int count = 0; _LifecycleAppPageState(this.str); @override void initState() { print(str); print('initState'); super.initState(); WidgetsBinding.instance.addObserver(this); } @override void didChangeDependencies() { print('didChangeDependencies'); super.didChangeDependencies(); } @override void didUpdateWidget(LifecycleAppPage oldWidget) { print('didUpdateWidget'); super.didUpdateWidget(oldWidget); } @override void deactivate() { print('deactivate'); super.deactivate(); } @override void dispose() { print('dispose'); WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { switch (state) { case AppLifecycleState.inactive: print('AppLifecycleState.inactive'); break; case AppLifecycleState.paused: print('AppLifecycleState.paused'); break; case AppLifecycleState.resumed: print('AppLifecycleState.resumed'); break; case AppLifecycleState.suspending: print('AppLifecycleState.suspending'); break; } super.didChangeAppLifecycleState(state); } @override Widget build(BuildContext context) { print('build'); return new Scaffold( appBar: new AppBar( title: new Text('lifecycle 学习'), centerTitle: true, ), body: new OrientationBuilder( builder: (context, orientation) { return new Center( child: new Text( '当前计数值:$count', style: new TextStyle( color: orientation == Orientation.portrait ? Colors.blue : Colors.red), ), ); }, ), floatingActionButton: new FloatingActionButton( child: new Text('click'), onPressed: () { count++; setState(() {}); }), ); } } class LifecyclePage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return new Scaffold( body: new LifecycleAppPage(), ); } }
flutter中的视图Widget像Android中的Activity一样存在生命周期,生命周期的回调函数体都在State中。
组件State的生命周期整理:
创建阶段
flutter:构造函数
f lutter: initState
flutter: didChangeDependencies
flutter: build
Widget状态改变
操作:横竖屏切换
Log所示:
其他生命周期并没有执行
竖屏切换到横屏执行2次
横屏切换到竖屏执行2次
fLutter:didupdatewidget
fLutter: build
flutter: didUpdatewidget
flutter: build
App切后台,再切回来
f lutter: AppLifecyclestate. inactive
flutter: AppLifecyclestate. paused
flutter: AppLifecyclestate. inactive
flutter: AppLifecycleState. resumed
销毁阶段
f lutter: deactivate
flutter: dispose