栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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
对。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/376072.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号