关于flutter生命周期的几个方法 initState、didChangeDependencies、dispose、didUpdateWidget
didChangeDependencies和dispose是配对的。
didChangeDependencies 会在不仅仅是initState后会调用,
修改widget key会删除和创建新的widget,调用dispose和didChangeDependencies。
不修改key则调用didUpdateWidget
测试代码:
class TitleWidget extends StatefulWidget {
const TitleWidget({Key? key}) : super(key: key);
@override
State<TitleWidget> createState() => _TitleWidgetState();
}
class _TitleWidgetState extends State<TitleWidget> {
@override
Widget build(BuildContext context) {
return Container(
height: 44,
child: Stack(
children: <Widget>[
Align(
alignment: Alignment.center,
child: GestureDetector(
onTap: () {
setState(() {}); //
},
child: TestWidget(
key: GlobalKey(),
),
),
),
Container(),
],
),
);
}
@override
void didChangeDependencies() {
// TODO: implement didChangeDependencies
super.didChangeDependencies();
print('didChangeDependencies');
}
@override
void didUpdateWidget(covariant TitleWidget oldWidget) {
// TODO: implement didUpdateWidget
super.didUpdateWidget(oldWidget);
print('didUpdateWidget');
}
@override
void initState() {
// TODO: implement initState
super.initState();
print('initstate');
}
}
class TestWidget extends StatefulWidget {
const TestWidget({Key? key}) : super(key: key);
@override
State<TestWidget> createState() => _TestWidgetState();
}
class _TestWidgetState extends State<TestWidget> {
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
void didChangeDependencies() {
// TODO: implement didChangeDependencies
super.didChangeDependencies();
print('didChangeDependencies');
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
print('dispose');
}
@override
void didUpdateWidget(covariant TestWidget oldWidget) {
// TODO: implement didUpdateWidget
super.didUpdateWidget(oldWidget);
print('didUpdateWidget');
}
@override
Widget build(BuildContext context) {
return Text(
'1234',
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold),
);
}
}
网友评论