【发布时间】:2019-12-28 15:22:33
【问题描述】:
我不想更改整个应用的文本颜色。只是容器内的所有文本。我可以用其他小部件或其他东西包装它吗?
【问题讨论】:
-
DefaultTextStyle? -
Text小部件有一个名为TextStyle的属性,它有一个名为color的属性
我不想更改整个应用的文本颜色。只是容器内的所有文本。我可以用其他小部件或其他东西包装它吗?
【问题讨论】:
DefaultTextStyle?
Text 小部件有一个名为 TextStyle 的属性,它有一个名为 color 的属性
仅将某些TextStyle 属性应用于应用程序的子树。你可以使用DefaultTextStyle
DefaultTextStyle(
child: Container(child: /* your subtree */),
style: TextStyle(color: Colors.red),
),
正如评论指出的那样,这将替换所有默认值,而不仅仅是颜色。这可以通过使用merge 构造函数来缓解:
DefaultTextStyle.merge(
child: Container(child: /* your subtree */),
style: TextStyle(color: Colors.red),
),
【讨论】:
在我看来,flutter 的回答很好。但ThemeData 的力量远超你的想象。这是关于应用程序部分主题的official documentation。
您可以提供Theme 来包装您的容器以提供新主题。这里有两种解决方法:
/*Not recommended, this could make a totally different If you just want a little part changed.*/
Theme(
// Create a unique theme with "ThemeData"
data: ThemeData(
textTheme: /* Your Text Theme*/,
),
child: Container(
onPressed: () {},
child: Text("Your Text Here"),
),
);
Theme(
// Find and extend the parent theme using "copyWith". See the next
// section for more info on `Theme.of`.
data: Theme.of(context).copyWith(textTheme: /* Provide your theme here! */),
child: Container(
child: Text("your text here"),
),
);
您也可以使用已存在的主题并稍作改动:
Theme.of(context).textTheme.copyWith(
body1: Theme.of(context).textTheme.body1.copyWith(color: Colors.red),
)
【讨论】:
Theme 包装一个小部件,由于某种原因这对我不起作用。
使用DefaultTextStyle.merge 保留您的主题并更改颜色。
DefaultTextStyle.merge(
style: TextStyle(color: Colors.grey[400]),
child: Column(...),
)
【讨论】:
如果您使用MaterialApp 小部件,您可以使用它的主题属性并设置不同的Text 主题并在应用程序的任何位置调用它们。例如下面的代码定义了 3 个不同的文本主题:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Time Tracker",
theme: ThemeData(
textTheme: TextTheme(
headline: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold,color: Colors.blue),
title: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic,color: Colors.red),
body1: TextStyle(fontSize: 14.0, fontFamily: 'Hind',color: Colors.yellow),
),
),
home: LandingPage(),
);
}
}
然后,您可以在应用中的任何位置调用特定主题(标题),如下所示:
Text('Home Page',style: Theme.of(context).textTheme.headline,)
哪个给你标题TextTheme
【讨论】:
我有适合我所有风格的功能
TextStyle largeTextStyle() => TextStyle(fontSize: 150);
那我就做吧
Text("blah", style:largeTextStyle())
【讨论】: