我为我的应用创建了以下主题:
ThemeData _buildDarkTheme() {
final baseTheme = ThemeData(fontFamily: "Sunflower",);
return baseTheme.copyWith(
brightness: Brightness.dark,
primaryColor: Colors.grey[800],
accentColor: Colors.grey[850]);
}
然后我将它应用到我的应用程序中,如下所示:
class MyApp extends StatelessWidget {
MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return new MaterialApp(
theme: _buildDarkTheme(),
home: new Scaffold(
appBar: _buildAppBar(),
body: new Container(
color: Theme.of(context).accentColor,
height: double.infinity,
child: new ListView.builder(...
但是,当我尝试访问容器内(或其他任何地方)的强调色而不是预期的颜色时,Colors.grey[850],它改为默认为蓝色。另外,尝试使用自定义字体 Sunflower 字体系列不起作用,但是当我改为使用时
new Text("Hello World", style: new TextStyle(fontFamily: "Sunflower"))
字体显示正确。
我是 flutter 和 dart 的新手,所以如果能帮助解决这些问题,我们将不胜感激。
最佳答案
这与 context
和 Theme.of
的工作方式有关。
来自Theme类源码:
static ThemeData of(BuildContext context, { bool shadowThemeOnly = false }) {
final _InheritedTheme inheritedTheme =
context.inheritFromWidgetOfExactType(_InheritedTheme);
if (shadowThemeOnly) {
if (inheritedTheme == null || inheritedTheme.theme.isMaterialAppTheme)
return null;
return inheritedTheme.theme.data;
}
final ThemeData colorTheme = (inheritedTheme != null) ? inheritedTheme.theme.data : _kFallbackTheme;
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final TextTheme geometryTheme = localizations?.localTextGeometry ?? MaterialTextGeometry.englishLike;
return ThemeData.localize(colorTheme, geometryTheme);
}
Theme.of
(以及 Navigator.of()、...
.of() 等),查看传递给它们的上下文,然后向上迭代查找指定类型的小部件的小部件树。
现在,看看你的代码
Widget build(BuildContext context) {
return new MaterialApp(
theme: _buildDarkTheme(),
home: new Scaffold(
appBar: _buildAppBar(),
body: new Container(
color: Theme.of(context).accentColor,
您可以看到您传递给 Theme.of
的 context
实际上是您正在创建的主题之上的上下文。所以它不会找到您的主题,并将恢复为默认值。这是因为小部件树看起来有点像以下(忽略所有中间层,箭头指向您正在使用的上下文。
MyApp - context <--------
MaterialApp
Theme
Scaffold
有两种方法可以解决此问题;第一种是使用 Builder
类在具有主题下方上下文的闭包中构建您的小部件。看起来像这样:
class MyApp extends StatelessWidget {
MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: _buildDarkTheme(),
home: Scaffold(
appBar: _buildAppBar(),
body: Builder(
builder: (context) => Container(
color: Theme.of(context).accentColor,
height: double.infinity,
child: ListView.builder(...)
),
),
),
);
}
}
它会生成一棵看起来像这样的树:
MyApp - context
MaterialApp
Theme
Scaffold
Builder - context <---------
另一个(首选)选项是将构建器的代码拆分为自己的类 - StatelessWidget
继承类或 StatefulWidget
和 状态
对。
关于dart - 自定义主题无法正常工作。 [ flutter ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50917350/