文章目录
Widget 系统
Flutter 的 UI 完全由 Widget 构成,Widget 是 Flutter 的核心概念。Widget 可以是按钮、文本、布局容器,甚至是整个页面。Flutter 的 Widget 系统非常灵活,通过组合和嵌套不同的 Widget 来构建复杂的 UI。
核心概念
1.1 StatelessWidget(静态 Widget)
- 特点:不可变,一旦创建就不能修改其状态。
- 适用场景:用于展示静态内容,例如文本、图标、按钮等。
- 示例:
class MyText extends StatelessWidget { Widget build(BuildContext context) { return Text('Hello, Flutter!'); } }
1.2 StatefulWidget(动态 Widget)
- 特点:可变,可以在运行时动态更新其状态。
- 适用场景:用于需要根据用户交互或数据变化更新的 UI,例如表单、计数器等。
- 示例:
class Counter extends StatefulWidget { _CounterState createState() => _CounterState(); } class _CounterState extends State<Counter> { int count = 0; void increment() { setState(() { count++; }); } Widget build(BuildContext context) { return Column( children: [ Text('Count: $count'), ElevatedButton( onPressed: increment, child: Text('Increment'), ), ], ); } }
必须掌握
1. Widget 的嵌套与组合
- 核心思想:Flutter 的 UI 是通过嵌套和组合多个 Widget 来构建的。
- 示例:
class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('My App')), body: Center( child: Column( children: [ Text('Hello, Flutter!'), ElevatedButton( onPressed: () {}, child: Text('Click Me'), ), ], ), ), ), ); } }
- 说明:
MaterialApp
是应用的根 Widget。Scaffold
提供了基本的页面结构(如 AppBar、Body)。Center
、Column
是布局 Widget,用于排列子 Widget。
2. BuildContext 的作用
- 定义:
BuildContext
是 Widget 在树中的位置信息,用于访问父级 Widget 的数据或服务。 - 用途:
- 访问主题(
Theme.of(context)
)。 - 导航(
Navigator.of(context)
)。 - 获取父级 Widget 的数据(
InheritedWidget
)。
- 访问主题(
- 示例:
class MyApp extends StatelessWidget { Widget build(BuildContext context) { final theme = Theme.of(context); // 获取主题 return Text('Hello', style: theme.textTheme.headline4); } }
3. 生命周期(initState、build、dispose)
- StatefulWidget 的生命周期:
createState
:创建 State 对象。initState
:初始化状态(只调用一次)。didChangeDependencies
:依赖变化时调用。build
:构建 UI(每次状态变化时调用)。setState
:触发 UI 更新。dispose
:销毁 State 对象(释放资源)。
- 示例:
class MyWidget extends StatefulWidget { _MyWidgetState createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { void initState() { super.initState(); print('Widget initialized'); } void dispose() { print('Widget disposed'); super.dispose(); } Widget build(BuildContext context) { return Text('Hello, Flutter!'); } }
总结
- StatelessWidget:用于静态 UI,不可变。
- StatefulWidget:用于动态 UI,可变。
- Widget 嵌套与组合:通过组合简单 Widget 构建复杂 UI。
- BuildContext:用于访问父级数据和服务。
- 生命周期:掌握
initState
、build
、dispose
等关键方法。
掌握这些知识点后,你可以轻松构建 Flutter 应用的 UI,并理解其运行机制。
结束语
Flutter是一个由Google开发的开源UI工具包,它可以让您在不同平台上创建高质量、美观的应用程序,而无需编写大量平台特定的代码。我将学习和深入研究Flutter的方方面面。从基础知识到高级技巧,从UI设计到性能优化,欢饮关注一起讨论学习,共同进入Flutter的精彩世界!