Flutter中如何简化Theme.of(context).colorScheme的重复书写?
问题
在Flutter开发中,每次获取当前主题颜色都要编写Theme.of(context).colorScheme.{具体颜色},几乎每一行用到颜色的地方都要重复这段代码,十分繁琐。即便在每个需要使用颜色的类的build()方法里定义变量final colorScheme = Theme.of(context).colorScheme,也还是要在每个类中重复编写这段代码。有没有办法制作一个可导入的缩写,能在整个文件的所有类中使用,避免重复编写相同内容?
解决方案
通过给BuildContext添加扩展方法,可以实现全局可复用的主题快捷访问,一次定义后,在任意导入该扩展的文件中都能直接使用。
扩展实现代码
import 'package:flutter/material.dart'; extension BuildContextExtensions on BuildContext { ThemeData get _theme => Theme.of(this); TextTheme get textTheme => _theme.textTheme; ColorScheme get colorScheme => _theme.colorScheme; Size get deviceSize => MediaQuery.sizeOf(this); }
使用步骤
- 在需要使用的文件中导入上述扩展所在的文件
- 直接通过
context.colorScheme访问主题配色方案,无需重复编写Theme.of(context)
使用示例
@override Widget build(BuildContext context) { return Container( color: context.colorScheme.primaryContainer, child: Text( '示例容器', style: TextStyle( color: context.colorScheme.onPrimaryContainer ) ) ); }
内容的提问来源于stack exchange,提问作者user21766581
相关产品推荐
相关产品推荐

