gpt4 book ai didi

Flutter 应用程序,Theme.of(context) 样式不适用于文本

转载 作者:行者123 更新时间:2023-12-04 01:03:24 24 4
gpt4 key购买 nike

尝试将文本颜色应用于 ListView 中的标题图块。我用红色文本颜色定义了标题文本样式(是的,我也用 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),
);

最佳答案

这是因为您使用传递给 Theme.of(context)MyApp 函数的相同上下文调用 build 。这意味着它返回的 ThemeData 将不是您为 MaterialApp 定义的那个。

当您通过调用 WidgetName.of(context) 获取小部件的状态时,您基本上使用该上下文向上查看小部件层次结构(该上下文所属的小部件的所有父级),直到找到该特定类型的小部件状态。您使用的上下文属于 MyApp 小部件,它是 MaterialApp 小部件的父级。

尝试使用 routesonGenerateRoute 而不是 home - 这将为您提供一个上下文来构建位于 MaterialApp 小部件下方的路线,以便当您调用 Theme.of(context) 时,它​​将返回预期的 ThemeData

关于Flutter 应用程序,Theme.of(context) 样式不适用于文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57666495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com