自定义主题无法正常工作。[扑]

自定义主题无法正常工作。[扑],第1张

自定义主题无法正常工作。[扑]

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,

您可以看到,

context
您传入
Theme.of
的实际上是您正在创建的主题上方的上下文。因此,它将找不到您的主题,并将恢复为默认主题。这是因为窗口小部件树看起来类似于以下内容(忽略所有中间层,其中箭头指向您正在使用的上下文)。

MyApp - context <--------  MaterialApp    Theme      Scaffold

有两种方法可以解决此问题;第一种是使用一个

Builder
类在闭包内构建您的窗口小部件,闭包具有位于主题下方的上下文。看起来像这样:

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 Builder(builder: (context) => new Container(      color: Theme.of(context).accentColor,      height: double.infinity,      child: new ListView.builder(...    ))

这将使一棵树看起来像这样:

MyApp - context  MaterialApp    Theme      Scaffold        Builder - context <---------

另一个(首选)选项是将构建器的代码拆分为自己的类-

StatelessWidget
继承的类或
StatefulWidget
and
State
对。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4920970.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存