RenderBox 的乾式布局支援
摘要
#一個名為 computeDryLayout
的新方法已加入 RenderBox
協議。RenderBox
的子類別應實作此方法,以便在固有計算期間,根據一組 BoxConstraints
正確回報其所需的尺寸。實作 computeDryLayout
的子類別不再需要覆寫 performResize
。
背景
#一個新的方法 computeDryLayout
,已加入 RenderBox
協議,以正確計算具有 WidgetSpan
子元件的 RenderParagraph
和 RenderWrap
的固有尺寸。此方法接收一組 BoxConstraints
,並應計算 RenderBox
的結果尺寸,而不會變更任何內部狀態。這本質上是 performLayout
的乾式執行,僅計算結果尺寸而不放置子元件。 computeDryLayout
方法是內在協議的一部分(另請參閱 RenderBox.computeMinIntrinsicWidth
及相關方法)。
變更說明
#如果 RenderBox
的子類別被用作可能查詢其子元件固有尺寸的 RenderObject
的後代,則需要覆寫新的 computeDryLayout
方法。這樣做的 widget 範例有 IntrinsicHeight
和 IntrinsicWidth
。
RenderBox.performResize
的預設實作也使用 computeDryLayout
計算的大小來執行調整大小。因此,不再需要覆寫 performResize
。
遷移指南
#可以透過簡單地將函式簽名從 void performResize()
變更為 Size computeDryLayout(BoxConstraints constraints)
並傳回計算的大小而不是將其指派給 size
setter 來遷移已經覆寫 performResize
的子類別。可以移除 performResize
的舊實作。
遷移前的程式碼
@override
void performResize() {
size = constraints.biggest;
}
遷移後的程式碼
// This replaces the old performResize method.
@override
Size computeDryLayout(BoxConstraints constraints) {
return constraints.biggest;
}
如果子類別沒有覆寫 performResize
,則必須從 performLayout
方法中提取 computeDryLayout
的實作。基本上,computeDryLayout
需要完成 performLayout
正在執行的所有工作,以找出 RenderBox
的大小。但是,它不是將其指派給 size
setter,而是傳回計算的大小。如果 computeDryLayout
需要知道其子元件的大小,則必須透過呼叫子元件上的 getDryLayout
而不是呼叫 layout
來取得該大小。
如果由於某些原因無法計算乾式布局,則 computeDryLayout
必須從斷言內呼叫 debugCannotComputeDryLayout
並傳回 const Size(0, 0)
的虛擬大小。例如,如果 RenderBox
的大小取決於其子元件的基準度量,則不可能計算乾式布局。
@override
Size computeDryLayout(BoxConstraints constraints) {
assert(debugCannotComputeDryLayout(
reason: 'Layout requires baseline metrics, which are only available after a full layout.'
));
return const Size(0, 0);
}
時間軸
#已納入版本:1.25.0-4.0.pre
在穩定版中:2.0.0
參考資料
#API 文件
RenderBox
computeMinInstrinsicWidth
computeDryLayout
getDryLayout
performResize
RenderWrap
RenderParagraph
相關議題
相關 PR
除非另有說明,否則本網站上的文件反映了 Flutter 的最新穩定版本。頁面上次更新時間為 2024-04-04。 檢視原始碼 或 回報問題。