ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
textStyle: TextStyle(color: Colors.black), // Not working
),
child: Text('Hello'),
)
Run Code Online (Sandbox Code Playgroud)
该方法中有textStyle
属性styleFrom
,但是当我为其提供颜色时,它不会改变所Text
提供的颜色。那么这个属性有什么用呢?
首先,如果我对Dart和Flutter的某些技术方面有一点不准确,我很抱歉:我对这些技术很陌生:)
\ntextStyle
方法中属性的用途styleFrom
是设置按钮上文本的样式。尽管如此,即使color
in属性的用途textStyle
是设置文本的颜色,也主要是为了Text
Widget的使用。在Button
s中,foregroundColor
有偏好。除此之外,设置的样式textStyle
将应用于按钮的文本(fontWeight
等)
设置foregroundColor
为null
并且color
属性 fromtextStyle
将被取而代之(继续阅读以获取详细信息!)。
所以,在我仔细阅读你的问题后,我很感兴趣并查阅了文档。在那里我发现
\n\n\n通常使用 [foregroundColor 属性] 代替 textStyle 的颜色。\n根据 ButtonStyle 值计算默认值的所有组件\n计算默认的foregroundColor 并使用它来代替\ntextStyle\ 的颜色。
\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\nonPrimary 和 onSurface 颜色用于创建\nMaterialStateProperty ButtonStyle.foregroundColor 值
\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在哪里
\nfinal ThemeData theme = Theme.of(context);\nfinal ColorScheme colorScheme = theme.colorScheme;\n
Run Code Online (Sandbox Code Playgroud)\n所以我意识到,在幕后,可能会通过从 中获取的方法foregroundColor
将值分配给onPrimary
set 。defaultStyleOf
Theme.of(context)
有了这些知识,我决定做一个实验并创建一个自定义按钮,ElevatedButton
该按钮将扩展defaultStyleOf
并覆盖onPrimary
设置为null
。通过这样做,按钮的foregroundColor
设置为null
,然后color
从textStyle
应该发挥作用,所以我写了
final ThemeData theme = Theme.of(context);\nfinal ColorScheme colorScheme = theme.colorScheme;\n
Run Code Online (Sandbox Code Playgroud)\n瞧\xc3\xa1!使用了 TextStyle 中的颜色!
\n\n