flutter - Dart 如何制作 MyClass.of(context) 方法

标签 flutter dart

假设我有这门课:

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 - Dart 如何制作 MyClass.of(context) 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57946592/

相关文章:

flutter - 如何在 flutter Dio 发布请求中的授权 header 中设置 token

flutter - FlutterIO 代码推送

flutter - ??操作符做什么?

flutter - 无法在 Flutter 中使用扩展运算符

dart - 如何在 Dart 组件中加入很棒的字体?

flutter - 如何在flutter中添加所需的参数

flutter - 在 showModalBottomSheet 外部单击时如何控制传递给 Navigator.pop() 的内容?

flutter - 如何在widgetTree之外访问rxdart-bloc函数?

dart - UI 测试按钮是否启用

image - 如何将 flutter photo_view 包与本地文件一起使用