在Flutter中为TextTheme添加可修改的属性

问题描述 投票:0回答:1

我正在尝试向 TextTheme 添加一个属性,我可以在 ThemeData 中修改该属性。我已经声明了以下扩展

extension CustomStyles on TextTheme{
  TextStyle get disabledText => const TextStyle(color: Color(0xff999999));
}

我可以使用它应用于文本字段

child: (_isEnabled)
  ? Text("Undo", style: Theme.of(context).textTheme.bodyMedium)
  : Text("Undo", style: Theme.of(context).textTheme.disabledText)

但是,当我尝试在 ThemeData 中访问它时(在与扩展相同的 dart 文件中声明)

theme: ThemeData (
  textTheme: TextTheme(
    bodyMedium: TextStyle(
      color: (_isDark) ? Colors.white : Colors.black,
      fontSize: _textSize
    ),
    disabledText: TextStyle(
      fontSize: _textSize
    ),
  ),
),

编译器给我错误

The named parameter 'disabledText' isn't defined

关于如何定义它以便我可以同时定义主题的颜色和大小有什么想法吗?

===更新===

因此,在 Dhafin 发表评论后,我现在通过声明带有颜色的静态变量并使用以下内容来解决这个问题

Text(item.text,
  style:          Theme.of(context).textTheme.bodyMedium!.copyWith(color: MyAppState.disabledText))

但问题仍然存在。必须有一种更优雅的方式来声明可以在任何地方访问的中心禁用主题

flutter flutter-theme
1个回答
0
投票

是的,编译器是对的。

您只在 TextTheme

 类上定义了 getter 方法

extension CustomStyles on TextTheme{
  TextStyle get disabledText => const TextStyle(color: Color(0xff999999));
}

此 getter 方法不是可以在通过扩展方法扩展的类的构造函数中传递的实例属性(数据成员)

TextTheme(
 disabledText: ..... // this data member is not defined.
 )

这就是为什么扩展方法称为 '扩展方法' 而不是 扩展属性 或一般扩展。

因此,对于您的问题:在扩展上提供

TextStyle
的所有视觉属性。

    extension CustomStyles on TextTheme{
      TextStyle get disabledText => const TextStyle(color: Color(0xff999999), fontSize: 20);
}

您可以通过以下方式访问它:

Theme.of(context).textTheme.disabledText

有关扩展方法的更多信息这里

希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.