开始修补Dart/Flutter,我正在尝试录制和播放音频。此库中提供的示例:https://github.com/dooboolab/flutter_sound 使用期货在 Dart 中显示异步代码。
Future<String> result = await flutterSound.startRecorder(null);
result.then(path) {
print('startRecorder: $path');
_recorderSubscription = flutterSound.onRecorderStateChanged.listen((e) {
DateTime date = new DateTime.fromMillisecondsSinceEpoch(e.currentPosition.toInt());
String txt = DateFormat('mm:ss:SS', 'en_US').format(date);
});
}
但是,这段代码甚至无法在我的系统上编译,所以我想知道我错过了什么。为了编译此代码,我必须将其更改为以下内容:
Future<String> result = widget._flutterSound.startRecorder(null);
result.then((path) {
print('startRecorder: $path');
var _recorderSubscription = widget._flutterSound.onRecorderStateChanged.listen((e) {
DateTime date = new DateTime.fromMillisecondsSinceEpoch(e.currentPosition.toInt());
print(date);
});
});
我错过了什么?
你试过这个吗:
Future<String> result() async => flutterSound.startRecorder(null);
当您使用期货:异步和等待:https://dart.dev/codelabs/async-await
时async和await关键字提供了一种声明性方法来定义异步函数并使用其结果。使用async和await时,请记住以下两个基本准则:
- 若要定义异步函数,请在函数体之前添加异步。
- await关键字仅适用于异步函数。