首页 > 解决方案 > 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();

标签: flutterdart

解决方案


当您已经可以轻松使用它时,我不确定您为什么需要这种方式

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();

推荐阅读