01——Flutter Widget框架概述

2021-04-08  本文已影响0人  转移到CSDN名字丹丹的小跟班

一. 介绍

Flutter Widget采用现代响应式框架构建,这是从 React 中获得的灵感,中心思想是用widget构建你的UI。 Widget描述了他们的视图在给定其当前配置和状态时应该看起来像什么。当widget的状态发生变化时,widget会重新构建UI,Flutter会对比前后变化的不同, 以确定底层渲染树从一个状态转换到下一个状态所需的最小更改(译者语:类似于React/Vue中虚拟DOM的diff算法)。

先来简单分析一个例子

import 'package:flutter/material.dart';

void main() {
  runApp(
    new Center(
      child: new Text(
        'Hello, world!',
        textDirection: TextDirection.ltr,
      ),
    ),
  );
}

在上面的代码里,好像并没有用到Widget类,但我们说了flutter渲染的ui是根据widget构建的,那Widget类型在哪呢?其实Center就是一个Widget类型,甚至里面的Tetx也是一个Widget类型。他们算是Widget的实例。可以在vscode按ctrl点击Center,会发现class Center extends Align,同理继续点击class Align extends SingleChildRenderObjectWidgetabstract class SingleChildRenderObjectWidget extends RenderObjectWidgetabstract class RenderObjectWidget extends Widget一层层点击后发现终于见到了Widget类(当然上面还有)。widget的主要工作是提供一个build()方法来描述如何构建UI界面(通常是通过组合、拼装其它基础widget)

以上代码就表示该runApp函数接受给定的Widget并使其成为widget树的根(也就是Center实例)。 在此示例中,widget树由两个widget:Center(及其子widget)和Text组成。框架强制根widget覆盖整个屏幕,这意味着文本“Hello, world”会居中显示在屏幕上。

总结Widget

二.Widget主要接口

聊了这么久的Widget,让我们来看看这个类的具体构造吧。

abstract class Widget extends DiagnosticableTree {
  /// Initializes [key] for subclasses.
  const Widget({ this.key });

  final Key? key;
  @protected
  @factory
  Element createElement();

  /// A short, textual description of this widget.
  @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;
  }

  static int _debugConcreteSubtype(Widget widget) {
    return widget is StatefulWidget ? 1 :
           widget is StatelessWidget ? 2 :
           0;
    }
}

有无状态的widget

另外Widget类本身是一个抽象类,其中最核心的就是定义了createElement()接口,在Flutter开发中,我们一般都不用直接继承Widget类来实现一个新组件,相反,我们通常会通过继承StatelessWidgetStatefulWidget来间接继承Widget类来实现。StatelessWidget和StatefulWidget都是直接继承自Widget类,而这两个类也正是Flutter中非常重要的两个抽象类,它们引入了两种Widget模型,接下来我们将重点介绍一下这两个类。
将上文的代码自己封装(继承的StatelessWidget类是一个抽象类,需要复写build方法,该方法需要返回一个widget类型)


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new Text(
        'Hello, world!',
        textDirection: TextDirection.ltr,
      ),
    );
  }
}

基础 Widget

Flutter有一套丰富、强大的基础widget,其中以下是很常用的:

上一篇 下一篇

猜你喜欢

热点阅读