Created with <3 with dartpad.dev.
Created
June 8, 2023 10:10
-
-
Save metal-young/aa5ced3f06d3dd71963e9c5045edce3d to your computer and use it in GitHub Desktop.
poetic-osmium-5535
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
String name = "未输入"; // 初始状态,未输入任何内容 | |
@override | |
void initState() { | |
super.initState(); | |
print('initState: 初始化状态'); // 打印生命周期状态 | |
} | |
@override | |
void didChangeDependencies() { | |
super.didChangeDependencies(); | |
print('didChangeDependencies: 在initState之后调用'); // 打印生命周期状态 | |
} | |
@override | |
void didUpdateWidget(covariant MyHomePage oldWidget) { | |
super.didUpdateWidget(oldWidget); | |
print('didUpdateWidget: 在widget配置改变时调用'); // 打印生命周期状态 | |
} | |
@override | |
void dispose() { | |
super.dispose(); | |
print('dispose: 在State对象从树中永久移除时调用'); // 打印生命周期状态 | |
} | |
@override | |
Widget build(BuildContext context) { | |
print('build: 响应在运行时发生的变化'); // 打印生命周期状态 | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Flutter 生命周期示例'), // 应用栏标题 | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Text( | |
'你好,$name', // 显示的文本,会随着用户输入的内容变化 | |
style: TextStyle(fontSize: 24), | |
), | |
Padding( | |
padding: const EdgeInsets.all(8.0), | |
child: TextField( | |
onChanged: (text) { | |
setState(() { | |
name = text; // 当用户输入内容时,更新name的值 | |
print('setState: 通知框架此对象的内部状态已更改'); // 打印生命周期状态 | |
}); | |
}, | |
decoration: InputDecoration( | |
labelText: '请输入你的名字', // 输入框的提示文本 | |
), | |
), | |
), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment