flutter - Dart 如何制作 MyClass.of(context) 方法
问题描述
说我有这门课:
class AppTheme {
final BuildContext context;
AppTheme(this.context);
TextStyle caption() {
return Theme.of(context).textTheme.caption.copyWith(
color: Colors.black
);
}
}
如何以我可以访问的方式修改它caption
:
AppTheme.of(context).caption();
解决方案
当您已经可以轻松使用它时,我不确定您为什么需要这种方式
AppTheme(context).caption();
但是如果你真的需要它,你可以试试这个:
class AppTheme {
final BuildContext context;
AppTheme._(this.context); // make this constructor private
static AppTheme of(BuildContext context) => AppTheme._(context); // pass context to above constructor
TextStyle caption() {
return Theme.of(context).textTheme.caption.copyWith(color: Colors.black);
}
}
你可以使用它
AppTheme.of(context).caption();
推荐阅读
- flutter - 在 Flutter 中接收到 token 后导航到主屏幕
- ajax - Google 图表不会基于新的 Ajax 过滤器重绘图表
- google-cloud-functions - 您可以运行可从公共 ip 访问的 /host firebase 模拟器吗?
- javascript - 为什么这个函数不触发?
- python - 使用 FRIDA Stalker 制作的指令计数器
- git - 安装git,哪个git版本没问题,还有一个$path Q
- java - iText7 - Html 到 PDF - 带页面计数器的页脚 - 如何更改颜色
- javascript - 计算旋转div的div宽度和高度
- elasticsearch - Elasticsearch:如何计算产量(成功百分比)?
- asp.net-core - Quartz.NET中接口的依赖注入以执行作业