ElevatedButton 中的 textStyle 属性有什么用?

iDe*_*ode 10 flutter

ElevatedButton(
  onPressed: () {},
  style: ElevatedButton.styleFrom(
    textStyle: TextStyle(color: Colors.black), // Not working
  ),
  child: Text('Hello'),
)
Run Code Online (Sandbox Code Playgroud)

该方法中有textStyle属性styleFrom,但是当我为其提供颜色时,它不会改变所Text提供的颜色。那么这个属性有什么用呢?

Dec*_*oth 6

首先,如果我对DartFlutter的某些技术方面有一点不准确,我很抱歉:我对这些技术很陌生:)

\n

简短回答

\n

textStyle方法中属性的用途styleFrom是设置按钮上文本的样式。尽管如此,即使colorin属性的用途textStyle是设置文本的颜色,也主要是为了TextWidget的使用。在Buttons中,foregroundColor有偏好。除此之外,设置的样式textStyle将应用于按钮的文本(fontWeight等)

\n

设置foregroundColornull并且color属性 fromtextStyle将被取而代之(继续阅读以获取详细信息!)。

\n

长答案

\n

所以,在我仔细阅读你的问题后,我很感兴趣并查阅了文档。在那里我发现

\n
\n

通常使用 [foregroundColor 属性] 代替 textStyle 的颜色。\n根据 ButtonStyle 值计算默认值的所有组件\n计算默认的foregroundColor 并使用它来代替\ntextStyle\ 的颜色。

\n
\n

好的,但是当我尝试从调用 styleFrom 方法的按钮检索 foregroundColor 属性时,我得到了 null

\n
...\nElevatedButton(\n  // prints null\n  onPressed: () {\n    print("foreground is ${ElevatedButton.styleFrom(textStyle: TextStyle(color: Colors.black)).foregroundColor}");\n  },\n...\n
Run Code Online (Sandbox Code Playgroud)\n

而且,textStyle 的颜色属性仍然被忽略,所以必须有其他东西......

\n

就在那时我意识到他们在文档中写道styleFrom

\n
\n

onPrimary 和 onSurface 颜色用于创建\nMaterialStateProperty ButtonStyle.foregroundColor 值

\n
\n

而且,进一步查看 ElevatedButton 的实现,我发现有一个名为 defaultStyleOf 的方法,该方法

\n
\n

定义按钮的默认外观。

\n
\n

更进一步,它的实现有这条线

\n
...\nreturn styleFrom(\n  primary: colorScheme.primary,\n  onPrimary: colorScheme.onPrimary,\n...\n
Run Code Online (Sandbox Code Playgroud)\n

在哪里

\n
final ThemeData theme = Theme.of(context);\nfinal ColorScheme colorScheme = theme.colorScheme;\n
Run Code Online (Sandbox Code Playgroud)\n

所以我意识到,在幕后,可能会通过从 中获取的方法foregroundColor将值分配给onPrimaryset 。defaultStyleOfTheme.of(context)

\n

有了这些知识,我决定做一个实验并创建一个自定义按钮,ElevatedButton该按钮将扩展defaultStyleOf并覆盖onPrimary设置为null。通过这样做,按钮的foregroundColor设置为null,然后colortextStyle应该发挥作用,所以我写了

\n
final ThemeData theme = Theme.of(context);\nfinal ColorScheme colorScheme = theme.colorScheme;\n
Run Code Online (Sandbox Code Playgroud)\n

瞧\xc3\xa1!使用了 TextStyle 中的颜色!

\n

在此输入图像描述

\n