【Flutter 學習筆記】🎬 教學影片:連結
【Flutter 學習筆記】📚 文章目錄:連結
今天我們將深入探討 Flutter 中的 Text 文字元件及其內部屬性。在上一堂課中,我們已經介紹了 Text 文字元件的基本用法,包括如何顯示文字內容和設定常見的文字樣式。這一堂課,我們將更進一步,了解 Text 文字元件的內部結構和屬性。
Ctrl
鍵並同時點擊 Text Widget;如果您是 Mac 使用者,則按下 Command
鍵並點擊 Text Widget。這樣一來,您就會跳轉到 Text 類別的原始碼定義頁面。除了在 Flutter 官網查看元件說明書外,筆者更推薦大家使用這種快速跳轉的方式來查看 Widget 的原始碼。這樣不僅直覺,還能幫助您更清楚地了解 Widget 的結構和內容。這個快速跳轉功能是非常實用的技巧,能幫助我們深入了解 Flutter 框架的運作原理。接下來,我們來看一下 Text 類別的原始碼。當您跳轉後,編輯器會自動打開 text.dart
檔案。Text Widget 是一個類別(class),它繼承自 StatelessWidget
,這意味著它是一個無狀態的 Widget。
class Text extends StatelessWidget {
/// Creates a text widget.
///
/// If the [style] argument is null, the text will use the style from the
/// closest enclosing [DefaultTextStyle].
///
/// The [overflow] property's behavior is affected by the [softWrap] argument.
/// If the [softWrap] is true or null, the glyph causing overflow, and those
/// that follow, will not be rendered. Otherwise, it will be shown with the
/// given overflow option.
const Text(
String this.data, {
super.key,
this.style,
this.strutStyle,
this.textAlign,
this.textDirection,
this.locale,
this.softWrap,
this.overflow,
@Deprecated(
'Use textScaler instead. '
'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. '
'This feature was deprecated after v3.12.0-2.0.pre.',
)
this.textScaleFactor,
this.textScaler,
this.maxLines,
this.semanticsLabel,
this.textWidthBasis,
this.textHeightBehavior,
this.selectionColor,
}) : textSpan = null,
assert(
textScaler == null || textScaleFactor == null,
'textScaleFactor is deprecated and cannot be specified when textScaler is specified.',
);
讓我們來看看 Text Widget 的建構子。建構子是一個特殊的函數,其名稱與類別名稱相同,主要用來初始化類別並創造新的實例。當我們在程式碼中使用 Text('HKT線上教室')
時,實際上是在建立一個新的 Text 類別的實例。
在 Dart 程式語言中,您不需要使用 new
關鍵字來建立新的實例,只需直接呼叫類別名稱即可。當您建立一個新的 Text Widget 時,建構子會自動被呼叫,並負責設定實例的初始狀態和屬性值。
在 Flutter 中,Widget 的建構子通常包含許多參數,讓我們能夠客製化 Widget 的外觀和行為。以 Text Widget 為例,它的建構子參數就有十幾個以上,每個參數都有其特定的用途。
如果某個參數標註了 @deprecated
,這表示該參數已經過時,Flutter 團隊建議使用其他新的參數來替代。
在 Text Widget 的建構子中,您會注意到有一個大括號 {}
。這表示裡面的參數是具名參數。具名參數的好處在於,當您有多個參數時,可以清楚地指定每個參數的用途。
例如,Text
函數中的 data
參數是我們要顯示的文字內容。這個參數位於大括號外,因此它是預設位置參數,您不需要具名來傳遞它。相對地,其他參數則需要具名來指定,例如設定文字樣式時,您需要寫成 style: ...
。
這樣的設計使得在傳遞多個參數時,程式碼更具可讀性,避免因為位置錯誤而導致的錯誤。