尝试将文本颜色应用于列表视图中的标题图块。我用红色文本颜色定义了标题文本样式(是的,我也尝试过使用 Colors.red)。
创建图块时,我使用函数 _headerTile。尝试通过 Theme.of(context).textTheme.headline 加载样式。但是,当我执行此操作时,文本不会使用我在标题中定义的三个属性中的任何一个。
我做错了什么吗?
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'App',
home: Scaffold(
appBar: AppBar(
title: const Text(
'App',
)),
body: _buildList(context)),
theme: ThemeData(
textTheme: TextTheme(
headline: TextStyle(
color: Color.fromRGBO(255, 0, 0, 1),
fontSize: 72.0,
fontWeight: FontWeight.bold),
),
));
}
}
Widget _buildList(BuildContext context) => ListView(
children: [
_headerTile(context, "About Us")
],
);
ListTile _headerTile(BuildContext context, String title) => ListTile(
title: Text(title,
style: Theme.of(context)
.textTheme
.headline
contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 8),
);
Run Code Online (Sandbox Code Playgroud)
这是因为您使用传递给s函数Theme.of(context)的相同上下文进行调用。这意味着它返回的将不是您为.MyAppbuildThemeDataMaterialApp
当您通过调用获取小部件的状态时WidgetName.of(context),您基本上使用该上下文在小部件层次结构中向上查找(该上下文所属的小部件的所有父级),直到找到该特定类型的小部件状态。您正在使用的上下文属于MyApp小部件,它是小部件的父级MaterialApp。
尝试使用routesoronGenerateRoute代替home- 这将为您提供一个上下文来构建位于MaterialApp小部件下方的路由,以便当您调用Theme.of(context)它时将返回预期的ThemeData.
您的文本不使用这三个属性中的任何一个,因为
.textTheme.headline 是在 text_theme.dart 中预定义的。当您定义
.textTheme.headline 时,它会根据
text_theme 文件中描述的预定义样式对其进行样式设置。您可以使用 .textTheme.display1 或 .textTheme.display2 查看更改
。如果您想要自定义样式,
可以这样做:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'App',
home: Scaffold(
appBar: AppBar(
title: const Text(
'App',
)),
body: Text("MyApp",style: heading,),
)
);
}
}
final heading = TextStyle(fontSize: 60.0,
fontWeight: FontWeight.bold,
color:Colors.green
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14854 次 |
| 最近记录: |