【问题标题】:How to write async getter with Flutter/Dart?如何使用 Flutter/Dart 编写异步 getter?
【发布时间】:2020-10-21 12:55:37
【问题描述】:

我正在 Flutter 中创建一个应用程序。 在这个应用程序中,我需要调用一个用 Java 编写的库。 现在,这个用 Java 编写的库有一个属性的 getter 和一个 setter。 我想从 Flutter/Dart 中调用这些 getter 和 setter,我们想使用它。

static const MethodChannel _channel = const MethodChannel('com.example.java-library');

static Future<String> get versionCode async {
  final String versionCode = await _channel.invokeMethod('getVersionCode');
  return versionCode;
}

static set versionCode(final String code) {
  _channel.invokeMethod('setVersionCode', code);
}

但是,如果我像上面那样编写代码,我会在运行时收到警告。

The return type of getter 'versionCode' is 'Future<String>' which isn't assignable to the type 'String' of its setter 'versionCode'.
Try changing the types so that they are compatible.

如何避免该问题,使警告不出现?

【问题讨论】:

  • 我遇到了同样的问题,你有解决方案吗?,当我更新 dart sdk 时会发生这种情况

标签: java flutter asynchronous dart


【解决方案1】:

使用这样的方法会更好:

static Future<String> getVersionCode() async {
  final String versionCode = await _channel.invokeMethod('getVersionCode');
  return versionCode;
}
static void setVersionCode(String code){
  _channel.invokeMethod('setVersionCode', code);
}

当你想检索(使用)该值时:

Future<void> anyOtherPlace()async{
   final String value = await getVersionCode();
}

【讨论】:

  • 你必须等待它,invokeMethod是异步的所以你必须等待它。
猜你喜欢
  • 1970-01-01
  • 2019-09-20
  • 1970-01-01
  • 2013-02-09
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
相关资源
最近更新 更多