flutter 常见组件的特殊用法 —— AppBar

2022/8/13 6:22:52

本文主要是介绍flutter 常见组件的特殊用法 —— AppBar,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

AppBar 的高度与 PreferredSizeWidget

通常可以观察到 Scaffold.appBar 与 AppBar.bottom 属性,要求其值必须是 PreferredSizeWidget(典型的是 AppBar 与 TabBar 组件)。

abstract class PreferredSizeWidget implements Widget {
  Size get preferredSize;
}

① 那么 AppBar 是怎么实现 PreferredSizeWidget 的呢?

  AppBar({
    Key? key,
    this.leading,
    this.automaticallyImplyLeading = true,
    this.title,
    //...
  }) : assert(automaticallyImplyLeading != null),
       //...
       // 这里即是实现
       preferredSize = _PreferredAppBarSize(toolbarHeight, bottom?.preferredSize.height),
       super(key: key);

class _PreferredAppBarSize extends Size {
  // kToolbarHeight 值是 56.0
  _PreferredAppBarSize(this.toolbarHeight, this.bottomHeight)
    : super.fromHeight((toolbarHeight ?? kToolbarHeight) + (bottomHeight ?? 0));

  final double? toolbarHeight;
  final double? bottomHeight;
}

可以看到 AppBar 的默认高度由 toolbarHeight(56.0) + bottomHeight 组成。

② 由于 bottom 组件通常是 TabBar,那么 TabBar 的默认高度是多少呢?

  @override
  Size get preferredSize {
    double maxHeight = _kTabHeight;
    for (final Widget item in tabs) {
      if (item is PreferredSizeWidget) {
        final double itemHeight = item.preferredSize.height;
        maxHeight = math.max(itemHeight, maxHeight);
      }
    }
    // indicatorWeight 默认高度是 2
    return Size.fromHeight(maxHeight + indicatorWeight);
  }

可以看到高度是 2 + tabs 的最大高度。

③ tabs 组件基础组件通常是 Tab,那么 Tab 的默认高度是多少呢?

  @override
  Size get preferredSize {
    if (height != null)
      return Size.fromHeight(height!);
    else if ((text != null || child != null) && icon != null)
      // _kTextAndIconTabHeight 是 72
      return const Size.fromHeight(_kTextAndIconTabHeight);
    else
      // _kTabHeight 是 46
      return const Size.fromHeight(_kTabHeight);
  }

即Tab有文字和图标时是 72,只有文字或图标时为 46。

④ 总结:AppBar 的高度是 104(56 + 48),其中 toolbarHeight 高度是 56(kToolbarHeight),bottom 组件 TabBar 组件高度通常是 48(46+2)(kTextTabBarHeight)。

特殊属性说明

primary: true

由前面的说明可知 AppBar 的高度由 toolbarHeight + bottomHeight 组成。默认情况下,该属性为 true,即总高度由 statusBar + toolbarHeight + bottomHeight 组成。

flexibleSpace 的布局不受此属性影响



这篇关于flutter 常见组件的特殊用法 —— AppBar的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程