我正在研究如何撰寫自己的小部件。我看過很多例子,它們都有一個繼承自 StatefulWidget 或 StatelessWidget 的 CustomWidget。是否可以從 Stack 或 TextBox 或我見過的從構建回傳的小部件之一繼承?我在想的是采用像 TextBox 這樣的小部件,添加自定義主題,然后將其匯出為新的小部件以供使用。
我看過很多使用 Material UI 的例子。對于我的需要,我需要一些不那么千篇一律的東西,讓我決定事物的外觀應該如何設計。
謝謝。
uj5u.com熱心網友回復:
是的,您可以創建一個擴展其他小部件的小部件,但您可能需要遵守其超級建構式。
你TextBox在你的問題中談論它,但它不是一個小部件,所以我猜你在談論Text小部件或類似的小部件。這是有關如何創建自己的小部件的代碼示例:
class MyText extends Text {
const MyText() : super("my-text"); // Need to pass a data value to the super constructor.
/// You can override the base build method to return a different widget,
/// in this case I am returning the base super.build (which will render
/// the Text widget) wrapped inside a red Container.
@override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
child: super.build(context),
);
}
}
在 DartPad 上嘗試完整的測驗代碼
uj5u.com熱心網友回復:
我在想的是采用像 TextBox 這樣的小部件,添加自定義主題,然后將其匯出為新的小部件以供使用。
然后,通過擴展TextBox來創建一個新的自定義小部件,這不是要走的路。
如果你這樣做,你將不得不對你的 TextBox 建構式的每個屬性進行硬編碼。做和維護都會很痛苦。
組合優于繼承中的 FLutter 基本原理。
因此,為了實作您的需求(主題),您只需要使用主題功能:
// global theming once and for all for all the app
MaterialApp(
theme: ThemeData(inputDecorationTheme: InputDecorationTheme()),
home: const MyHomePage(),
);
或者
// located theme overload just for here
Theme(data: Theme.of(context).copyWith(inputDecorationTheme: InputDecorationTheme()), child: TextFormField());
僅主題化可能還不夠,但您確實應該避免繼承復雜的本機小部件,更喜歡屬性分解的組合
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/391672.html
