In the async codelab:
Ref: https://dart.dev/codelabs/async-await
They have the following snippet:
Future<void> printOrderMessage() async {
print('Awaiting user order...');
var order = await fetchUserOrder();
print('Your order is: $order');
}
Future<String> fetchUserOrder() {
// Imagine that this function is more complex and slow.
return Future.delayed(const Duration(seconds: 4), () => 'Large Latte');
}
void main() async {
countSeconds(4);
await printOrderMessage();
}
Based on the logic of printOrderMessage() I've made a similar function:
void main() async {
int? value;
value = await test();
print(value);
}
Future<int?> test() async{
print('Function has started');
Future.delayed(Duration(milliseconds: 2000), () {
return 4;
});
}
In my case, it prints Function has started null. why doesn't it wait for the value to be populated
Future<int?> test() async {
print('Function has started');
await Future.delayed(Duration(milliseconds: 2000), () {});
return 4;
}
Future<int?> test() async {
print('Function has started');
return Future.delayed(Duration(milliseconds: 2000), () {
return 4;
});
}
Related
void main() {
test('simple', () async {
await fakeAsync((async) async {
final stream = Stream.value(42);
print('hi before await');
await stream.toList();
print('hi after await');
});
});
}
stucks forever in the toList line...
I have also tried to call whatever methods, but still stuck forever in the "await" line
test('simple', () async {
await fakeAsync((async) async {
final stream = Stream.value(42);
final future = stream.toList();
print('hi before await');
async.flushMicrotasks();
async.flushTimers();
async.elapse(const Duration(seconds: 10));
async.elapseBlocking(const Duration(seconds: 10));
await future;
print('hi after await');
});
});
I have looked at the implementation of Stream.toList as follows, but it seems quite normal
Future<List<T>> toList() {
List<T> result = <T>[];
_Future<List<T>> future = new _Future<List<T>>();
this.listen(
(T data) {
result.add(data);
},
onError: future._completeError,
onDone: () {
future._complete(result);
},
cancelOnError: true);
return future;
}
In C# I can use async and await to process tasks in parallel. I can kick off an asynchronous task, do other things, and finally await for the asynchronous task to complete.
var t = myFunctionAsync();
executeTask1();
executeTask2();
await t;
How can I do this in dart/flutter?
Reference: async-await
void main() async {
var t = myFunctionAsync();
executeTask1();
executeTask2();
await t;
}
Future<int> myFunctionAsync() async {
await Future.delayed(const Duration(seconds: 2));
return 2;
}
void executeTask1() {
// do something
}
void executeTask2() {
// do something
}
void someFunction () async{
executeTask1();
executeTask2();
await executeTask3();
}
How do you check if an async void method is completed in Dart?
Method 1:
await voidFoo();
print("the above function was completed");
Future<void> voidFoo() async{
await Future.delayed(Duration(seconds:1));
}
Method 2:
Using a boolean variable like this,
bool isCompleted = false;
...
await voidFoo();
Future<void> voidFoo() async{
await Future.delayed(Duration(seconds:1));
isCompleted = true; //assuming isCompleted can be accessed here
}
There are too many methods to do this
i prefer to do this
Future<void> myFunction() async {
await Future.delayed(Duration(seconds: 3)); // your future operation
}
main() async {
await myFunction();
print("finished");
}
You can use dart Completer.
import 'dart:async';
void main() async {
final completer = Completer<String>();
Future<String> getHttpData()async{
return Future.delayed(const Duration(seconds: 1), () => "Future Result");
}
Future<String> asyncQuery()async {
final httpResponse = await getHttpData();
completer.complete(httpResponse);
return completer.future;
}
print('IsCompleted: ${completer.isCompleted}');
await asyncQuery();
print('IsCompleted: ${completer.isCompleted}');
}
Result;
IsCompleted: false
IsCompleted: true
Hello I am trying to run following code, I want to run a specific asynchronous code and show alert dialog until it's running. But the code is not being executed after await showAlertDialog(); this line.
void appendAndRunPythonCode() async {
await showAlertDialog();
await runPythonScript(final_code);
_alertDialogUtils.dismissAlertDialog(context);
}
This is how my showAlertDialog() function is implemented:
Future<void> showAlertDialog() async {
if (!_alertDialogUtils.isShowing) {
await _alertDialogUtils.showAlertDialog(context);
}
}
runPythonCode():
Future<void> runPythonScript(String code) async {
if (inputImg == null) {
ToastUtils.showToastMessage(text: ConstUtils.input_image_empty_notice);
return;
}
if (code.isEmpty) {
ToastUtils.showToastMessage(text: ConstUtils.code_empty);
return;
}
List<String> lines = code.split('\n');
String lastLine = lines.elementAt(lines.length - 4);
if (lastLine.split(' ').elementAt(0).compareTo('outputImage') != 0) {
ToastUtils.showToastMessage(text: ConstUtils.cv_error_line2);
return;
}
data.putIfAbsent("code", () => code);
data.putIfAbsent("inputImg", () => inputImg);
_alertDialogUtils.showAlertDialog(context);
final result = await _channel.invokeMethod("runPythonCVScript", data);
// Add Artifical Delay of 3 seconds..
await Future.delayed(
Duration(seconds: 3),
);
_alertDialogUtils.dismissAlertDialog(context);
setState(
() {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
curve: Curves.easeOut,
duration: const Duration(milliseconds: 300),
);
output = result['textOutput'] ??= "";
error = result['error'] ??= "";
outputImg = (result['graphOutput']);
data.clear();
},
);
}
You shouldn't await the showAlertDialog because runPythonScript won't be executed until the dialog is dismissed.
Remove the await.
Like so:
void appendAndRunPythonCode() async {
showAlertDialog();
await runPythonScript(final_code);
_alertDialogUtils.dismissAlertDialog(context);
}
I was experimenting with asynchronous programming in dart when I stumbled upon a problem in which when I put a return statement inside a Future.delayed function it doesn't seem to return a value.
void main() {
perform();
}
void perform() async {
String result = await firstTask();
finalTask(result);
}
Future firstTask() async {
Duration duration = Duration(seconds: 4);
String result = 'task 2 data';
await Future.delayed(duration, () {
print('First Task Completed');
return result;
});
}
void finalTask(String result) {
print('final task completed and returned $result');
}
but if I put the return result; statement outside the Future.delayed function it returns its value to task 3. like,
void main() {
perform();
}
void perform() async {
String result = await firstTask();
finalTask(result);
}
Future firstTask() async {
Duration duration = Duration(seconds: 4);
String result = 'task 2 data';
await Future.delayed(duration, () {
print('First Task Completed');
});
return result;
}
void finalTask(String result) {
print('final task completed and returned $result');
}
Your first task doesn't have any return statement. IDE should be warning you about it. To fix it you have to do
Future firstTask() async {
Duration duration = Duration(seconds: 4);
String result = 'task 2 data';
return await Future.delayed(duration, () {
print('First Task Completed');
return result;
});
}
Or
Future firstTask() { // No async here
Duration duration = Duration(seconds: 4);
String result = 'task 2 data';
return Future.delayed(duration, () {
print('First Task Completed');
return result;
});
}