先给结果,在看代码。 简单易懂。
flutter widget的布局信息是存在父widget里面的
结果
flutter: build
flutter: 1.调用HYHomeContent的constructor方法
flutter: 2.调用HYHomeContent的createState方法
flutter: 3.调用_HYHomeContentState的constructor方法
flutter: 4.调用_HYHomeContentState的initState方法
flutter: 调用_HYHomeContentState的didChangeDependencies方法
flutter: 5.调用_HYHomeContentState的build方法
flutter: build
flutter: 1.调用HYHomeContent的constructor方法
flutter: didUpdateWidget
flutter: 5.调用_HYHomeContentState的build方法
代码
import 'package:flutter/material.dart';
main() => runApp(MyApp());
class MyAppextends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home:HYHomeDemo(),
);
}
}
class HYHomeDemoextends StatefulWidget {
@override
_HYHomeDemoState createState() =>_HYHomeDemoState();
}
class _HYHomeDemoStateextends State {
@override
Widget build(BuildContext context) {
print("build");
return Scaffold(
appBar:AppBar(
title:Text("商品列表"),
),
body:Column(
children: [
HYHomeContent()
],
),
floatingActionButton:RaisedButton(
child:Icon(Icons.add),
onPressed: () {
setState(() {
});
},
),
);
}
}
// StatelessWidget的生命周期
// class HYHomeContent extends StatelessWidget {
// final String message;
// HYHomeContent(this.message) {
// print("构造函数被调用");
// }
// @override
// Widget build(BuildContext context) {
// print("调用build方法");
// return Text(message);
// }
// }
// StatefulWidget的生命周期
class HYHomeContentextends StatefulWidget {
HYHomeContent() {
print("1.调用HYHomeContent的constructor方法");
}
@override
_HYHomeContentState createState() {
print("2.调用HYHomeContent的createState方法");
return _HYHomeContentState();
}
}
class _HYHomeContentStateextends State {
int_counter =0;
_HYHomeContentState() {
print("3.调用_HYHomeContentState的constructor方法");
}
@override
void initState() {
// 调用: 这里是必须调用super
final TextStyle style =TextStyle();
super.initState();
print("4.调用_HYHomeContentState的initState方法");
}
@override
void didUpdateWidget(HYHomeContent oldWidget) {
super.didUpdateWidget(oldWidget);
print("didUpdateWidget");
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
print("调用_HYHomeContentState的didChangeDependencies方法");
}
@override
Widget build(BuildContext context) {
print("5.调用_HYHomeContentState的build方法");
return Column(
children: [
RaisedButton(
child:Icon(Icons.add),
onPressed: () {
setState(() {
_counter++;
});
},
),
Text("数字:$_counter")
],
);
}
@override
void dispose() {
print("6.调用_HYHomeContentState的dispose方法");
super.dispose();
}
}
网友评论