繁体   English   中英

如何使用 Flutter/Dart 编写异步 getter?

[英]How to write async getter with Flutter/Dart?

我正在 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.

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

最好使用这样的方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM