如何在顫振中創建自定義 TextStyle 類?例如,我有幾個按鈕,希望里面的文本都具有相同的 fontSize 和顏色,但我不想在每個 Text 小部件中重復 TextStyle,而是創建一些東西,例如我可以使用的 CustomTextStyle 代替TextStyle 本身。有沒有辦法做到這一點?
uj5u.com熱心網友回復:
創建一個單獨的類名 CustomTextStyle 并在其中添加樣式,例如:
class CustomTextStyle {
static const TextStyle nameOfTextStyle = TextStyle(
fontSize: 24,
color: Colors.green,
fontWeight: FontWeight.bold,
);
}
現在您可以在 Text 小部件中使用它,例如:
Text('Lorem Ipsum',
style: CustomTextStyle.nameOfTextStyle,
)
uj5u.com熱心網友回復:
要全域定義按鈕或文本樣式,您需要使用主題。
例如,您可以為以下內容定義自定義主題TextButton:
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
textButtonTheme: TextButtonThemeData(
style: ButtonStyle(
textStyle: MaterialStateProperty.all(
const TextStyle(fontSize: 20),
),
),
),
[...]
uj5u.com熱心網友回復:
有三種方法可以做到這一點:
使用主題:
您可以在 Theme 中基于小部件分別宣告多個 TextStyles,例如
AppBar'sTitleTextTheme、AppBar'sToolbarTextTheme、Button'sTextTheme、 GeneralTextTheme用于整個應用程式,或者基于ThemeMode,例如 Dark Mode 或 Light 模式,您可以將這兩個 Widgets based 和 ThemeModes 結合起來也有依據。為此,請創建一個名為
ThemeModel例如的類,在其中創建ThemeData變數,您將在其中宣告這些 TextThemes 并在您的MaterialAppin 中使用它main.dart作為MaterialApp( ..., theme: ThemeModel().lightMode, darkTheme: ThemeModel().darkMode, )使用自定義文本小部件。
const CustomText extends StatelessWidget { final String text; const CustomText(this.text, {Key? key}): super(key:key); @override Widget build(BuildContext context) { return Text( text, style: TextStyle( color: YourColor, fontSize: YourSize, fontWeight: YourFontWeight ), );并將其用作,
ElevatedButton( onPressed: (){}, child: CustomText('Click Me'), )這樣,
TextStyle無論您在何處使用此小部件,它都將保持不變。使用自定義
TextStyle:class CustomTextStyle { static const TextStyle textStyle = TextStyle( color: YourColor, fontSize: YourSize, fontWeight: YourFontWeight ); }并且,將其用作:
ElevatedButton( onPressed: (){}, child: Text('Click Me', style: CustomTextStyle.textStyle, ), )
希望您了解這些方法中的每一種都有自己的實用程式,并且可以進一步自定義方式以簡化您的應用程式開發。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/467978.html
上一篇:BlocListener混淆
