我是旦旦i
V1
2022/06/05阅读:14主题:自定义主题1
Flutter中的Widget
Widget 的简单说明
Flutter 的所有对象几乎都是一个 widget, widget 不仅可以标识 UI 元素,也可以表示一些功能性组件,比如:
-
用于手势检测的 GestureDetector -
用于 App 主题数据传递的 Theme -
......
Flutter 中是通过 Widegt 嵌套 Widget 来构建 UI 和进行实践处理的。
Widget 的作用
widget 的功能是 描述构建 Element 元素的配置信息。
widget 是 Flutter 框架中的中心类层次结构、小部件本身没有可变状态。
Widget 的结构
@immutable // 不可变的
abstract class Widget extends DiagnosticableTree {
const Widget({ this.key });
final Key? key;
@protected
@factory
Element createElement();
@override
String toStringShort() {
final String type = objectRuntimeType(this, 'Widget');
return key == null ? type : '$type-$key';
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.defaultDiagnosticsTreeStyle = DiagnosticsTreeStyle.dense;
}
@override
@nonVirtual
bool operator ==(Object other) => super == other;
@override
@nonVirtual
int get hashCode => super.hashCode;
static bool canUpdate(Widget oldWidget, Widget newWidget) {
return oldWidget.runtimeType == newWidget.runtimeType
&& oldWidget.key == newWidget.key;
}
...
}
Flutter 框架的的处理流程
-
根据 Widget 树生成一个 Element 树,Element 树种的节点都继承自 Elemnet 类。 -
根据 Element 树生成 Render 树(渲染树),渲染树中的节点都继承自 RenderObject 类。 -
根据渲染树生成 Layer 树,然后上屏显示,Layer 树种的节点都继承自 Layer 类。
真正的布局和渲染逻辑在 Render 树中,Element 是 Widget 和 RenderObject 的粘合剂,可以理解为一个中间代理,如下:
Container( // 一个容器 widget
color: Colors.blue, // 设置容器背景色
child: Row( // 可以将子widget沿水平方向排列
children: [
Image.network('https://www.example.com/1.png'), // 显示图片的 widget
const Text('A'),
],
),
);
参考文章:
-
https://api.flutter.dev/flutter/widgets/Widget-class.html -
https://docs.flutter.dev/development/ui/widgets-intro -
https://book.flutterchina.club/chapter2/flutter_widget_intro.html#_2-2-3-flutter%E4%B8%AD%E7%9A%84%E5%9B%9B%E6%A3%B5%E6%A0%91
作者介绍
我是旦旦i
V1