英文:
Futures in Dart / flutter_sound examples not working
问题
开始尝试使用Dart/Flutter,我正在尝试录制和播放音频。此库中提供的示例:https://github.com/dooboolab/flutter_sound 展示了在Dart中使用Futures的异步代码。
Future<String> result = await flutterSound.startRecorder(null);
result.then((path) {
print('startRecorder: $path');
var _recorderSubscription = flutterSound.onRecorderStateChanged.listen((e) {
DateTime date = new DateTime.fromMillisecondsSinceEpoch(e.currentPosition.toInt());
print(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);
});
});
我漏掉了什么?
英文:
Start tinkering with Dart/Flutter, I'm trying to record and play audio. Examples provided in this library: https://github.com/dooboolab/flutter_sound show async code in Dart using Futures.
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);
});
}
However this code doesn't even compile at my system so Im wondering what I'm missing. In order to compile this code I have to change it to something like:
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);
});
});
What am I missing?
答案1
得分: 1
你试过这样做吗:
Future<String> result() async => flutterSound.startRecorder(null);
当你使用 futures 时,可以使用 async 和 await:https://dart.dev/codelabs/async-await
async 和 await 关键字提供了一种声明式的方式来定义异步函数并使用它们的结果。在使用 async 和 await 时,请记住以下两个基本准则:
- 要定义一个异步函数,在函数体前加上 async。
- await 关键字只能在 async 函数中使用。
英文:
Have you try this:
Future<String> result() async => flutterSound.startRecorder(null);
when you working with futures: async and await: https://dart.dev/codelabs/async-await
> The async and await keywords provide a declarative way to define asynchronous functions and use their results. Remember these two basic guidelines when using async and await:
>
> - To define an async function, add async before the function body.
> - The await keyword works only in async functions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论