flutter - 在 Flutter 本地干净地覆盖部分主题

我有一个小部件,它有两个 TextField 作为后代。我想对这些 TextField 应用相同的样式。我的理解是,正确的方法是将本地化主题应用于我的小部件树。以下是我的尝试。这是来 self 的根小部件的 build 函数的代码片段。有没有更清洁的方法来做到这一点?

final ThemeData _themeData = Theme.of(context);
return Theme( // HACK
  data: _themeData.copyWith(
    inputDecorationTheme: InputDecorationTheme(
      border: OutlineInputBorder(),
    ),
    textTheme: _themeData.textTheme.copyWith(
      subhead: _themeData.textTheme.subhead.copyWith(
        fontSize: 30.0,
      ),
    ),
  ),
  child: _buildTheRestOfMyWidgetTree(context),
);

让我恼火的是,要覆盖单个属性(_themeData.textTheme.subhead.fontSize),我必须显式手动复制三个中间数据结构(_themeData,然后是 _themeData.textTheme,然后是 _themeData.textTheme.subhead)。

最佳答案

虽然我可以理解不得不“复制”所有内容的挫败感,但你应该这样做。

数据在 Flutter 中是不可变的。你不能改变它们,你不得不用不同的属性克隆它们。

因此你的假设是正确的:如果你想修改一个嵌套属性,你也必须克隆它的所有父级。这导致:

final ThemeData theme = Theme.of(context);
theme.copyWith(
  textTheme: theme.textTheme.copyWith(
    subhead: theme.textTheme.subhead.copyWith(
      fontSize: 30.0,
    ),
  ),
);

再说一遍:你无法避免。

https://stackoverflow.com/questions/52345077/

相关文章:

text - 如何为 Text 小部件 Flutter 实现 OnPressed 回调

layout - flutter 中从右到左(RTL)

android - 没有权限(plugdev 组中的用户;你的 udev 规则错了吗?)

flutter - debugPaintSizeEnabled 在 Flutter 中不起作用

logging - Dart/flutter 错误 : 'toStringDeep' isn't d

flutter - 如何在 Ios 上更改状态栏文本颜色

dart - 没有 AppBar 的 Flutter TabBar

flutter - flutter 中带有圆角的警报对话框

error-handling - 如何在 flutter 中使用 bloc 模式进行错误处理?

dart - 转换时间戳