Flutter:Builder 构造器

Builder组件

文档如下:

class Builder extends StatelessWidget {
  /// Creates a widget that delegates its build to a callback.
  ///
  /// The [builder] argument must not be null.
  const Builder({
    Key key,
    @required this.builder,
  }) : assert(builder != null),
       super(key: key);

  /// Called to obtain the child widget.
  ///
  /// This function is called whenever this widget is included in its parent's
  /// build and the old widget (if any) that it synchronizes with has a distinct
  /// object identity. Typically the parent's build method will construct
  /// a new tree of widgets and so a new Builder child will not be [identical]
  /// to the corresponding old one.
  final WidgetBuilder builder;

  @override
  Widget build(BuildContext context) => builder(context);
}

如果翻阅flutter源码的话可以看到很多源码中很多组件都是依赖于Builder实现的,那么Builder价值何在?

Builder 是一个继承自 Stateless 的组件,需要实现 build 抽象方法,通过 BuildContext 对象,来构建 Widget 对象。而 Builder#build 只是使用了构造传入的 builder 函数,并将 当前的 BuildContext 作为回调传递出去。也就是将构建组件的逻辑交由外界处理,自身只是将 context 对象回调出去而已。

所以 Builder 组件唯一的价值,就是回调当前的 context ,让用户根据这个 context 进行组件的构建。

你可能感兴趣的:(Flutter:Builder 构造器)