【问题标题】:Flutter assign Theme text styleFlutter 分配 Theme 文本样式
【发布时间】:2021-10-26 00:41:17
【问题描述】:

我想知道有没有比这种方法更好的方法来将我的主题的某种默认文本样式分配给 Text 小部件。

Text(
 'Hello world',
  style: Theme.of(context).textTheme.headline1,
),

我确实认为应该有类似单独的小部件或文本方法 Text.headline1 或简单的样式命令样式:TextStyle.headline1。

但似乎我必须通过 Theme.of(context) 才能得到这个。

谁有更好的解决方案?

【问题讨论】:

    标签: flutter text themes simplify


    【解决方案1】:

    你可以直接使用TextStyle:

    Text(
     'Hello world',
      style: TextStyle(color: Colors.black, fontSize: 15.0), // Etc...
    ),
    

    【讨论】:

    • 嗨鲍里斯,这并不反映我可能交换主题的意图。谢谢你的回复。
    【解决方案2】:

    Theme.of(context) 是一个很好的选择,原因有很多,比如在浅色和深色主题之间切换。我喜欢为主题和文本主题创建一个变量,以保持简洁高效。

    Widget build(BuildContext context) {
      final theme = Theme.of(context);
      final textTheme = theme.textTheme;
    
      return Column(
        children: [
          Text('Heading Text', style: textTheme.headline1),
          Text('Caption Text', style: textTheme.caption),
          Text('Body text...', style: textTheme.bodyText1),
        ],
      );
    }
    

    【讨论】:

    • 谢谢,Jared,我也考虑过创建一个变量。然而,它仍然是涉及上下文的相同方法,如果没有全局定义,您可能想要使用它的每个类仍然需要它。
    【解决方案3】:

    Theme.of 返回为最近的BuildContext 祖先指定的ThemeData 值。如果您不使用它,那么您将无法访问您可能设置的主题配置并受益于它的优势。

    但是,您可以创建一个名为 Styles 的类,您可以在其中访问预定义的颜色、文本样式等:

    class Styles {
      static const Color primaryColor = Colors.blue;
    
      static const TextStyle headline1 = TextStyle(
        fontSize: 20.0,
        fontWeight: FontWeight.bold,
      );
    
      static const TextStyle bodyText1 = TextStyle(
        fontSize: 16.0,
        fontWeight: FontWeight.normal,
      );
    }
    

    这是一个使用它的例子:

    Text(
      'Hello world',
      style: Styles.headline1,
    )
    

    【讨论】:

    • 这需要为已定义的主题中的现有参数定义一个额外的样式,因此如果我想交换主题,会产生额外的维护工作。
    猜你喜欢
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 2021-12-25
    • 2020-02-07
    • 1970-01-01
    • 2011-03-22
    相关资源
    最近更新 更多