我有一个小部件,有两个TextFields作为后代.我想将相同的样式应用于这些TextField.我的理解是,正确的方法是将本地化主题应用于我的小部件树.以下是我的尝试.这是我的根小部件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),
);
Run Code Online (Sandbox Code Playgroud)
我烦恼的是,为了覆盖单个属性(_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,
),
),
);
Run Code Online (Sandbox Code Playgroud)
再次:您无法避免。
| 归档时间: |
|
| 查看次数: |
1307 次 |
| 最近记录: |