Flutter學(xué)習(xí) - 布局原理篇

前言

這篇博客主要探討Flutter布局的相關(guān)原理,分為兩個大部分当编,單child容器的布局和多child容器布局届慈。

布局基本法則

一個Widget的布局主要有四個步驟

  • 當(dāng)前Widget從父Widget獲取到約束
  • 當(dāng)前Widget向子級Widget傳遞約束,子級通過約束確定自身大小
  • 當(dāng)前Widget綜合子級Widget大小和自身大小確定子級Widget位置
  • 當(dāng)前Widget將尺寸信息傳遞給父Widget凌箕,完成閉環(huán)

單child容器

案例分析

比如Center組件拧篮,我們按照基本法則進(jìn)行分析

  1. Center拿到父Widget的約束,同時確定自己的寬高為最大可取寬高牵舱,也就是填充滿父Widget
  2. Center告訴子Widget可以取任意寬高串绩,子Widget根據(jù)約束得到尺寸,并告知Center
  3. Center根據(jù)子Widget和自身尺寸確定子Widget位置芜壁,也就是居中
  4. Center將自身尺寸信息傳遞給父Widget

使用CustomSingleChildLayout模擬Center

單child容器中有一個特殊的容器CustomSingleChildLayout礁凡,可以用來自定義布局,通過它我們可以更清晰的感受布局流程慧妄。

首先定義一個繼承自SingleChildLayoutDelegate的類并且實現(xiàn)四個方法

getSize

此方法用于獲取自身的大小顷牌,方法會將父Widget的約束傳遞下來,也就是對應(yīng)第一步

Size getSize(BoxConstraints constraints) {
  print("get size: $constraints");
  return constraints.biggest;
}

這里取的是constraints.biggest塞淹,也就是填充滿父Widget

getConstraintsForChild

為子Widget生成約束窟蓝,這里minWidthminHeight都設(shè)置為0, 表示允許子Widget在父Widget的尺寸范圍內(nèi)可以取任意大小

BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
  final relaxConstraint = BoxConstraints(
      minWidth: 0,
      minHeight: 0,
      maxWidth: constraints.maxWidth,
      maxHeight: constraints.maxHeight);
  return relaxConstraint;
}

getPositionForChild

這個方法告知了我們當(dāng)前Widget的尺寸和子Widget的尺寸饱普,通過這兩個尺寸可以很容易得計算出居中的位置

Offset getPositionForChild(Size size, Size childSize) {
  return Offset((size.width - childSize.width) * 0.5,
      (size.height - childSize.height) * 0.5);
}

綜合在一起

class CustomCenterDelegate extends SingleChildLayoutDelegate {
  final double xFactor;
  final double yFactor;
  CustomCenterDelegate({this.xFactor = 0, this.yFactor = 0});

  // 自己的大小
  Size getSize(BoxConstraints constraints) {
    print("get size: $constraints");
    return constraints.biggest;
  }

  // 子widgte的約束
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
    final relaxConstraint = BoxConstraints(
        minWidth: 0,
        minHeight: 0,
        maxWidth: constraints.maxWidth,
        maxHeight: constraints.maxHeight);
    print("getConstraintsForChild: ${relaxConstraint}}");
    return relaxConstraint;
  }

  // 子widgte的位置
  Offset getPositionForChild(Size size, Size childSize) {
    print("getPositionForChild");
    return Offset((size.width - childSize.width) * (xFactor + 1) * 0.5,
        (size.height - childSize.height) * (1 + yFactor) * 0.5);
  }

  // 是否需要重繪
  bool shouldRelayout(covariant SingleChildLayoutDelegate oldDelegate) {
    return false;
  }
}

其中有一個shouldRelayout表示是否需要重新布局运挫。由于Center就是居中,沒有調(diào)整的參數(shù)套耕,所以不需要在delegate改變時重新布局谁帕,這里就返回false。如果是類似于Align的布局冯袍,需要在alignment改變時重新布局匈挖,這里就需要判斷alignment是否改變了碾牌。最后簡單的封裝一下,就可以和Center一樣使用了儡循。

class CustomCenter extends StatelessWidget {
  final Widget? child;
  const CustomAlign(
      {super.key, this.child});

  @override
  Widget build(BuildContext context) {
    return CustomSingleChildLayout(
      delegate: CustomCenterDelegate(),
      child: child,
    );
  }
}

更進(jìn)一步舶吗,源碼分析

進(jìn)一步分析源碼,可以發(fā)現(xiàn)CustomSingleChildLayout主要依賴于RenderCustomSingleChildLayoutBox

@override
RenderCustomSingleChildLayoutBox createRenderObject(BuildContext context) {
  return RenderCustomSingleChildLayoutBox(delegate: delegate);
}

@override
void updateRenderObject(BuildContext context, RenderCustomSingleChildLayoutBox renderObject) {
  renderObject.delegate = delegate;
}

RenderCustomSingleChildLayoutBox中的核心則是performLayout贮折,performLayout的代碼簡單明了

@override
void performLayout() {
  // 當(dāng)前Widget從父Widget獲取到約束裤翩,確定自身大小
  size = _getSize(constraints);
  if (child != null) {
    // 當(dāng)前Widget向子級Widget傳遞約束
    final BoxConstraints childConstraints = delegate.getConstraintsForChild(constraints);
    assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true));
    // 子級通過約束確定自身大小
    child!.layout(childConstraints, parentUsesSize: !childConstraints.isTight);
    final BoxParentData childParentData = child!.parentData! as BoxParentData;
    // 當(dāng)前Widget綜合子級Widget大小和自身大小確定子級Widget位置
    childParentData.offset = delegate.getPositionForChild(size, childConstraints.isTight ? childConstraints.smallest : child!.size);
  }
}

多child容器

案例分析

多child的布局會復(fù)雜很多,比如Row組件调榄,他的布局過程如下

  1. 將所有flex為0的 子Widgets(比如非Expanded)布局踊赠,使用的約束為主軸(mainAxis)不限制,交叉軸(crossAxis)使用傳入的交叉軸約束
  2. 將剩余的主軸空間按照flex不為0的Widgets比例分割每庆,比如三個flex為1的Widget筐带,主軸方向上各得到1/3
  3. flex不為0的Widgets使用分到的主軸長度和傳入的交叉軸約束進(jìn)行布局
  4. Row的高度取子Widget最高
  5. Row的寬度和mainAxisSize有關(guān),如果是max缤灵,則取父Widget的最大寬伦籍,min則取子Widgets寬度之和
  6. 根據(jù)mainAxisAlignment和crossAxisAlignment進(jìn)行子Widgets位置計算

按照基本布局法則做映射的話

  • 當(dāng)前Widget從父Widget獲取到約束 => 使用了父Widget的交叉軸約束
  • 當(dāng)前Widget向子級Widget傳遞約束,子級通過約束確定自身大小 => 1,2,3步總的來說就是給不同子Widget分配不同約束腮出,從而計算子Widget尺寸
  • 當(dāng)前Widget綜合子級Widget大小和自身大小確定子級Widget位置 => 4帖鸦,5,6通過子Widget反算Row寬高胚嘲,從而進(jìn)一步?jīng)Q定子Widget位置
  • 當(dāng)前Widget將尺寸信息傳遞給父Widget作儿,完成閉環(huán) => Row的最終大小會被傳遞給父Widget做上層的布局

Row源碼分析

接下來我們對照Row的源碼來進(jìn)一步感受布局的過程,Row繼承自Flex馋劈,F(xiàn)lex中真正進(jìn)行布局的是RenderFlex類的performLayout方法

@override
  void performLayout() {
    ...
    // 計算子Widgets的尺寸攻锰,包含1,2妓雾,3三個步驟
    final _LayoutSizes sizes = _computeSizes(
      layoutChild: ChildLayoutHelper.layoutChild,
      constraints: constraints,
    );
    ...

    // 根據(jù)計算的尺寸設(shè)置子Widget位置
    // Position elements
    double childMainPosition = flipMainAxis ? actualSize - leadingSpace : leadingSpace;
    RenderBox? child = firstChild;
    while (child != null) {
      final FlexParentData childParentData = child.parentData! as FlexParentData;
      final double childCrossPosition;
      switch (_crossAxisAlignment) {
        case CrossAxisAlignment.start:
        case CrossAxisAlignment.end:
          childCrossPosition = _startIsTopLeft(flipAxis(direction), textDirection, verticalDirection)
                               == (_crossAxisAlignment == CrossAxisAlignment.start)
                             ? 0.0
                             : crossSize - _getCrossSize(child.size);
        case CrossAxisAlignment.center:
          childCrossPosition = crossSize / 2.0 - _getCrossSize(child.size) / 2.0;
        case CrossAxisAlignment.stretch:
          childCrossPosition = 0.0;
        case CrossAxisAlignment.baseline:
          if (_direction == Axis.horizontal) {
            assert(textBaseline != null);
            final double? distance = child.getDistanceToBaseline(textBaseline!, onlyReal: true);
            if (distance != null) {
              childCrossPosition = maxBaselineDistance - distance;
            } else {
              childCrossPosition = 0.0;
            }
          } else {
            childCrossPosition = 0.0;
          }
      }
      if (flipMainAxis) {
        childMainPosition -= _getMainSize(child.size);
      }
      switch (_direction) {
        case Axis.horizontal:
          childParentData.offset = Offset(childMainPosition, childCrossPosition);
        case Axis.vertical:
          childParentData.offset = Offset(childCrossPosition, childMainPosition);
      }
      if (flipMainAxis) {
        childMainPosition -= betweenSpace;
      } else {
        childMainPosition += _getMainSize(child.size) + betweenSpace;
      }
      child = childParentData.nextSibling;
    }
  }

再來分析下_computeSizes的實現(xiàn)
第一步就是計算flex為0的子Widgets尺寸

double crossSize = 0.0;
double allocatedSize = 0.0; // Sum of the sizes of the non-flexible children.
RenderBox? child = firstChild;
RenderBox? lastFlexChild;
while (child != null) {
  final FlexParentData childParentData = child.parentData! as FlexParentData;
  final int flex = _getFlex(child);
  if (flex > 0) {
    totalFlex += flex;
    lastFlexChild = child;
  } else {
    final BoxConstraints innerConstraints;
    if (crossAxisAlignment == CrossAxisAlignment.stretch) {
      switch (_direction) {
        case Axis.horizontal:
          innerConstraints = BoxConstraints.tightFor(height: constraints.maxHeight);
        case Axis.vertical:
          innerConstraints = BoxConstraints.tightFor(width: constraints.maxWidth);
      }
    } else {
      switch (_direction) {
        case Axis.horizontal:
          innerConstraints = BoxConstraints(maxHeight: constraints.maxHeight);
        case Axis.vertical:
          innerConstraints = BoxConstraints(maxWidth: constraints.maxWidth);
      }
    }
    final Size childSize = layoutChild(child, innerConstraints);
    allocatedSize += _getMainSize(childSize);
    crossSize = math.max(crossSize, _getCrossSize(childSize));
  }
  assert(child.parentData == childParentData);
  child = childParentData.nextSibling;
}

可以看到如果是flex大于0娶吞,則統(tǒng)計flex到totalFlex中。對于flex為0的Widget則只針對cross方向構(gòu)造約束進(jìn)行布局械姻。如果cross對齊是stretch模式妒蛇,則使用tight約束保證cross方向撐滿

if (crossAxisAlignment == CrossAxisAlignment.stretch) {
      switch (_direction) {
        case Axis.horizontal:
          innerConstraints = BoxConstraints.tightFor(height: constraints.maxHeight);
        case Axis.vertical:
          innerConstraints = BoxConstraints.tightFor(width: constraints.maxWidth);
      }
    } else {
      switch (_direction) {
        case Axis.horizontal:
          innerConstraints = BoxConstraints(maxHeight: constraints.maxHeight);
        case Axis.vertical:
          innerConstraints = BoxConstraints(maxWidth: constraints.maxWidth);
      }
    }

第二步開始計算flex大于0的子Widgets尺寸

// Distribute free space to flexible children.
final double freeSpace = math.max(0.0, (canFlex ? maxMainSize : 0.0) - allocatedSize);
double allocatedFlexSpace = 0.0;
// totalFlex大于0表示有flex不為0的子Widget
if (totalFlex > 0) {
  final double spacePerFlex = canFlex ? (freeSpace / totalFlex) : double.nan;
  child = firstChild;
  while (child != null) {
    final int flex = _getFlex(child);
    if (flex > 0) {
      // 計算出這個子Widget在主軸可被分配的最大尺寸
      final double maxChildExtent = canFlex ? (child == lastFlexChild ? (freeSpace - allocatedFlexSpace) : spacePerFlex * flex) : double.infinity;
      late final double minChildExtent;
      // 針對FlexFit分配不同約束,這就是Expanded和Flexible的區(qū)別楷拳,Expanded采用FlexFit.tight模式材部,F(xiàn)lexible則是FlexFit.loose
      switch (_getFit(child)) {
        case FlexFit.tight:
          assert(maxChildExtent < double.infinity);
          minChildExtent = maxChildExtent;
        case FlexFit.loose:
          minChildExtent = 0.0;
      }
      // 這塊和flex為0基本一致,為子Widget構(gòu)建約束唯竹,計算尺寸
      final BoxConstraints innerConstraints;
      if (crossAxisAlignment == CrossAxisAlignment.stretch) {
        switch (_direction) {
          case Axis.horizontal:
            innerConstraints = BoxConstraints(
              minWidth: minChildExtent,
              maxWidth: maxChildExtent,
              minHeight: constraints.maxHeight,
              maxHeight: constraints.maxHeight,
            );
          case Axis.vertical:
            innerConstraints = BoxConstraints(
              minWidth: constraints.maxWidth,
              maxWidth: constraints.maxWidth,
              minHeight: minChildExtent,
              maxHeight: maxChildExtent,
            );
        }
      } else {
        switch (_direction) {
          case Axis.horizontal:
            innerConstraints = BoxConstraints(
              minWidth: minChildExtent,
              maxWidth: maxChildExtent,
              maxHeight: constraints.maxHeight,
            );
          case Axis.vertical:
            innerConstraints = BoxConstraints(
              maxWidth: constraints.maxWidth,
              minHeight: minChildExtent,
              maxHeight: maxChildExtent,
            );
        }
      }
      final Size childSize = layoutChild(child, innerConstraints);
      final double childMainSize = _getMainSize(childSize);
      assert(childMainSize <= maxChildExtent);
      allocatedSize += childMainSize;
      allocatedFlexSpace += maxChildExtent;
      crossSize = math.max(crossSize, _getCrossSize(childSize));
    }
    final FlexParentData childParentData = child.parentData! as FlexParentData;
    child = childParentData.nextSibling;
  }
}

最后一步,通過計算出來的子Widget尺寸苦丁,計算Row的尺寸浸颓,這里主要就是判斷mainAxisSize,看需要最大值還是真實的子Widget寬度和。

final double idealSize = canFlex && mainAxisSize == MainAxisSize.max ? maxMainSize : allocatedSize;

CustomMultiChildLayout

最后再介紹一個用于自定義多child布局的Widget产上,和單child類似棵磷,需要實現(xiàn)一個delegate

class CustomRowDelegate extends MultiChildLayoutDelegate {
  @override
  void performLayout(Size size) {
    
  }

  @override
  bool shouldRelayout(covariant MultiChildLayoutDelegate oldDelegate) {
    
  }
}

方法很簡單,就2個晋涣,這里需要注意的是仪媒,和上面介紹的Row布局不同,這里能夠布局的尺寸已經(jīng)固定了谢鹊,子Widget無法影響CustomMultiChildLayout的尺寸算吩,CustomMultiChildLayout的尺寸就是performLayout傳遞的Size。

比如我們想要實現(xiàn)一個橫向自動均分子Widget的容器佃扼,可以這么寫

@override
void performLayout(Size size) {
  if (keys != null) {
    // 對橫向的空間進(jìn)行均分
    final childWidth = size.width / keys!.length;
    var offsetX = 0.0;
    for (final String key in keys!) {
      // 橫向構(gòu)造嚴(yán)格約束偎巢,縱向構(gòu)造寬松約束,從而讓子Widget橫向使用均分的尺寸兼耀,縱向使用自己的尺寸
      final constraits = BoxConstraints(minWidth: childWidth, maxWidth: childWidth, minHeight: 0, maxHeight: size.height);
      final childSize = layoutChild(key, constraits);
      // 對于縱向讓子Widget居中
      positionChild(key, Offset(offsetX, (size.height - childSize.height) * 0.5));
      offsetX += childSize.width;
    }
  }
}

CustomMultiChildLayout規(guī)定每個子Widget必須都是LayoutId

(id: "1", child: Container(height: 60, color: Colors.yellow,),),

在布局子Widget時以它的id作為憑證

final childSize = layoutChild(key, constraits);

最后使用這個自定義的Widget

class CustomRow extends StatelessWidget {
  final List<Widget>? children;
  final List<String>? keys;
  const CustomRow(
      {super.key, this.children, this.keys});

  @override
  Widget build(BuildContext context) {
    return CustomMultiChildLayout(
      delegate: CustomRowDelegate(keys: keys),
      children: children ?? [],
    );
  }
}

...

CustomRow(
  keys: const ["1", "2", "3"],
  children: [
    LayoutId(id: "1", child: Container(height: 60, color: Colors.yellow,),),
    LayoutId(id: "2", child: Container(height: 80, color: Colors.red,),),
    LayoutId(id: "3", child: Container(height: 40, color: Colors.green,),),
  ],
),

總結(jié)

通過對布局原理的了解压昼,在布局的時候可以更加清晰的預(yù)測UI的效果,每當(dāng)遇到一個新布局Widget瘤运,就可以通過四個步驟去梳理他的布局過程窍霞,通過文檔和開源的代碼,就可以很深入的掌握它的特性了拯坟。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末但金,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子似谁,更是在濱河造成了極大的恐慌傲绣,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件巩踏,死亡現(xiàn)場離奇詭異秃诵,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)塞琼,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進(jìn)店門菠净,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人彪杉,你說我怎么就攤上這事毅往。” “怎么了派近?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵攀唯,是天一觀的道長。 經(jīng)常有香客問我渴丸,道長侯嘀,這世上最難降的妖魔是什么另凌? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮戒幔,結(jié)果婚禮上吠谢,老公的妹妹穿的比我還像新娘。我一直安慰自己诗茎,他們只是感情好工坊,可當(dāng)我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著敢订,像睡著了一般王污。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上枢析,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天玉掸,我揣著相機(jī)與錄音,去河邊找鬼醒叁。 笑死司浪,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的把沼。 我是一名探鬼主播啊易,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼饮睬!你這毒婦竟也來了租谈?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤捆愁,失蹤者是張志新(化名)和其女友劉穎割去,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體昼丑,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡呻逆,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了菩帝。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片咖城。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖呼奢,靈堂內(nèi)的尸體忽然破棺而出宜雀,到底是詐尸還是另有隱情,我是刑警寧澤握础,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布辐董,位于F島的核電站,受9級特大地震影響禀综,放射性物質(zhì)發(fā)生泄漏郎哭。R本人自食惡果不足惜他匪,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望夸研。 院中可真熱鬧,春花似錦依鸥、人聲如沸亥至。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽姐扮。三九已至,卻和暖如春衣吠,著一層夾襖步出監(jiān)牢的瞬間茶敏,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工缚俏, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留惊搏,地道東北人。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓忧换,卻偏偏與公主長得像恬惯,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子亚茬,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容