【问题标题】:How to create a global TextStyle in Flutter?如何在 Flutter 中创建全局 TextStyle?
【发布时间】:2021-02-11 07:47:29
【问题描述】:

在返回语句之前的构建小部件的主页中,我使用以下代码。 如果我在主页中创建另一个小部件,我必须在每个返回语句之前复制以下代码。如果您创建另一个无状态/有状态 dart 文件,我需要再次复制以下代码。

我的问题是如何在 Flutter 中创建全局 TextStyle?我不想更改主题数据,都想在我的颤振项目中使用我的 TextStyle。谢谢。

  TextStyle myNormalStyle = TextStyle(
        fontSize: SizerUtil.deviceType == DeviceType.Mobile ? 14.0.sp : 13.0.sp,
        fontStyle: FontStyle.normal,
        fontWeight: FontWeight.normal,
        color: Colors.black);

【问题讨论】:

    标签: flutter global-variables textstyle


    【解决方案1】:

    您可以使用Theme 轻松使用。如flutter docs 所述,您可以像这样使用它:

    MaterialApp(
      title: title,
      theme: ThemeData(
        // Define the default brightness and colors.
        brightness: Brightness.dark,
        primaryColor: Colors.lightBlue[800],
        accentColor: Colors.cyan[600],
    
        // Define the default font family.
        fontFamily: 'Georgia',
    
        // Define the default TextTheme. Use this to specify the default
        // text styling for headlines, titles, bodies of text, and more.
        textTheme: TextTheme(
          headline1: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
          headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
          bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
        ),
      )
    );
    

    或者您也可以使用DefaultTextStyle 小部件为该小部件的所有子级提供默认TextStyle。阅读更多关于DefaultTextStyle的信息。

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 2021-10-19
      • 2021-02-28
      • 1970-01-01
      • 2020-06-04
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      相关资源
      最近更新 更多