StatelessWidget:无状态部件的生命周期
import 'package:flutter/material.dart';void main() {runApp(App());
}class App extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(home: MyHomePage(title: 'MyHome'),);}
}class MyHomePage extends StatelessWidget {final String? title;MyHomePage({this.title}) {print('MyHomePage:构造函数被调用了');}@overrideWidget build(BuildContext context) {print('build:被调用了');return Center(child: Text(title!),);}
}
// 执行顺序:MyHomePage:构造函数被调用了 -> build:被调用了
StatefulWidget:有状态部件的生命周期
import 'package:flutter/material.dart';void main() {runApp(App());
}class App extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(home: MyHomePage(title: 'MyHome'),);}
}class MyHomePage extends StatefulWidget {final String? title;MyHomePage({this.title}) {print('Widget:构造函数被调用');}@overrideState<MyHomePage> createState(){print('createState:被调用');return _MyHomePageState();}
}class _MyHomePageState extends State<MyHomePage> {// 这个方法一般忽略不写_MyHomePageState(){print('State 的 _MyHomePageState:构造函数被调用');}@overridevoid initState() {print('State 的 initState:被调用');super.initState();}@overridevoid didChangeDependencies() {print('didChangeDependencies:被调用(改变依赖关系)');super.didChangeDependencies();}@overrideWidget build(BuildContext context) {print('build:被调用');return Center(child: Text(widget.title!),);}@overridevoid dispose() {print('State 的 dispose:销毁被调用');super.dispose();}
}// 执行顺序:
Widget:构造函数被调用
createState:被调用
State 的 _MyHomePageState:构造函数被调用
State 的 initState:被调用
didChangeDependencies:被调用(改变依赖关系) // 下一篇文章会配合:InheritedWidget数据共享,一起使用
build:被调用当离开页面
当Widget销毁时:State 的 dispose:被调用// 如果在有状态的组件中 更新数据,需要调用:setState会重新调用build进行渲染
setState(() {});