[英]Flutter: Theme not applied to Text Widget
我正在尝试制作一个仅适用于该主题的子项的自定义主题。
但是,当我运行该应用程序时,显示“你好”的文本小部件仍然是蓝色的。 我想让它变黄。
谁能告诉我我哪里出错了?
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
brightness: Brightness.dark,
primaryColor: Colors.lightBlue[800],
accentColor: Colors.cyan[600],
textTheme: TextTheme(body1: TextStyle(color: Colors.blue))),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text(widget.title),
),
body: Center(
child: Theme(
data: Theme.of(context).copyWith(
textTheme:
TextTheme(body1: TextStyle(color: Colors.yellow))),
child: Text("hello"))));
}
}
要主题化Text
您需要将值分配给style
属性
Text("Hello", style: Theme.of(context).textTheme.body1)
确保在执行Theme.of(context)
时使用正确的context
。 您需要一个作为新Theme
子代的context
。
您需要执行以下操作:
Theme(
child: Builder(
builder: (context) {
return Text("Hello", style: Theme.of(context).textTheme.body1);
}
)
)
这是另一种方式,因为有时覆盖默认样式更方便
文本小部件:
如果
style
参数为 null,则文本将使用最近的封闭DefaultTextStyle
的样式。
@override
Widget build(BuildContext context) {
final DefaultTextStyle defaultTextStyle = DefaultTextStyle.of(context);
TextStyle effectiveTextStyle = style;
if (style == null || style.inherit)
effectiveTextStyle = defaultTextStyle.style.merge(style);
所以,如果你想覆盖Text
小部件的默认样式(当你不传递style
属性时),你需要使用DefaultTextStyle
小部件
return new Scaffold(
appBar: new AppBar(
title: Text(widget.title),
),
body: Center(
child: DefaultTextStyle(
style: Theme.of(context).textTheme.body1.copyWith(color: Colors.yellow),
child: Text("hello"))
)
);
MaterialApp
使用它的TextStyle
作为它的DefaultTextStyle
来鼓励开发者有意识地使用他们的DefaultTextStyle
最新的 Flutter Release 标记body1
已弃用,所以现在我们可以使用bodyText2
:
Text("My Text", style: Theme.of(context).textTheme.bodyText2)
新参数(正确的是新的)
body2 => bodyText1;
body1 => bodyText2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.