How do you check if an async void method is completed in Dart? - flutter

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

Related

How to use async/await in Dart for parallel processing

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 to pass data between isolates in flutter dart

I am buiding an app were I want to run a batch operation in firestore and I want to run it in a different isolate. Here is my code for spawning the isolate:
Future<void> _startAnotherIsolate(String mediaUrl) async {
final isolate = await FlutterIsolate.spawn(isolate1,"hello"); // i need to pass 2 more
arguments
Timer(Duration(seconds: 5), () {
print("Pausing Isolate 1");
isolate.pause();
});
Timer(Duration(seconds: 10), () {
print("Resuming Isolate 1");
isolate.resume();
});
Timer(Duration(seconds: 20), () {
print("Killing Isolate 1");
isolate.kill();
});
}
My code for the isolate:
void isolate1(String data1, String data2) async {
await Firebase.initializeApp();
print("changing profile picture: $phone");
Timer.periodic(Duration(seconds: 1), (timer) => print("Timer Running From Isolate 1"));
var db = FirebaseFirestore.instance;
var batch = db.batch();
FirebaseFirestore.instance.collection("posts").doc(phone).collection("userPosts")
.get().then((querySnapshot) {
for (var document in querySnapshot.docs) {
try {
batch.update(document.reference,{'user_image': mediaUrl});
} on FormatException catch (error) {
// If a document ID is unparsable. Example "lRt931gu83iukSSLwyei" is unparsable.
// print("The document ${error.source} could not be parsed.");
return null;
}
}
return batch.commit();
});
}
I have seen This link and this link but they are not helpful
import 'dart:isolate';
class RequiredArgs {
late final SendPort sendPort;
late int id;
RequiredArgs(this.id, this.sendPort);
}
Future<void> main() async {
ReceivePort receivePort = ReceivePort();
RequiredArgs requiredArgs = RequiredArgs(1122, receivePort.sendPort);
Isolate isolate = await Isolate.spawn(download, requiredArgs);
var resp = await receivePort.first;
print(resp);
}
void download(RequiredArgs requiredArgs) {
final SendPort sendPort = requiredArgs.sendPort;
final id = requiredArgs.id;
print(id);
sendPort.send("yes");
}
We pass the value using the RequiredArgs class. Hope my answer helps.

Flutter/Dart convert future bool to bool

Can some one help me to identify the issue in below piece of code
void main() async {
bool c =getstatus();
print(c);
}
Future<bool> getMockData() {
return Future.value(false);
}
bool getstatus() async
{
Future<bool> stringFuture = getMockData();
bool message = stringFuture;
return(message); // will print one on console.
}
To get values from a Future(async) method, you have to await them. And after await the variable you get is not a Future anymore. So basically your code should look like this:
void main() async {
bool c = await getstatus();
print(c);
}
Future<bool> getMockData() {
return Future.value(false);
}
Future<bool> getstatus() async {
bool message = await getMockData();
return message;
}
Future<bool> stringFuture = await getMockData();
an async method must return Future of something then in the main you have to get the bool value by writing await
void main() async {
bool c = await getstatus();
print(c); // will print false on the console.
}
Future<bool> getMockData() {
return Future.value(false);
}
Future<bool> getstatus() async {
Future<bool> stringFuture = await getMockData();
return stringFuture; // will return false.
}

Asynchronous method not running in proper order

I have these methods, for some reason fetchItems is being called first before initPosition, how come dart wont wait for it to finish and proceeds to the second method? I've added async/await but it still doesn't work. I've also checked my backend logs to confirm this. Am I doing something wrong?
Future<void> initPosition() async {
if (_latitude != null && _longitude != null) {
await Socket.updatePosition(
lat: 51,
lon: 17,);
}
}
Future<void> initMarkers() async {
await initPosition();
await Provider.of<Items>(context, listen: false)
.fetchItems();
}
void initMapState() async {
await getCurrentLocation().then((_) async {
await initMarkers();
setState(() {
_loaded = true;
});
});
}
#override
void initState() {
super.initState();
_location.enableBackgroundMode(enable: false);
WidgetsBinding.instance?.addPostFrameCallback((_) {
initMapState();
});
}
Future<void> fetchItems() async {
itemList = await repository.getItemList();
notifyListeners();
}
Working with multiple asynchronous functions inside Futures depends on whether one is finished or not, not every single one. For this, you can call the "whenComplete" method so you can assure that your future function have finished running. Like this:
For your initMarkers() function:
Future<void> initMarkers() async {
await initPosition().whenComplete((){
Provider.of<Items>(context, listen: false)
.fetchItems();
});
}
For your initMapState() function:
void initMapState() async {
await getCurrentLocation().whenComplete(() async {
await initMarkers().whenComplete((){
setState(() {
_loaded = true;
});
});
});
}
Keep in mind that, in your code, you are not working with the returning value of your getCurrentLocation() function, so instead of using the "then" method use the "whenComplete" method, assuring that you changed or returned your values with this function. Finally, for the initState(), make the function body with asynchronous:
#override
void initState() {
super.initState();
_location.enableBackgroundMode(enable: false);
WidgetsBinding.instance?.addPostFrameCallback((_) async {
initMapState();
});
}
This should work.

Flutter:How I create a Hive DAO class in flutter/dart?

I need to group all operations of a Hivebd crud get, put, delete and update in one class but when I try this get a error because Hive.openBox() need an await but constructors not allowed async.How I would do that corectely?
My class below.
class HomeListRepository {
var _homelistStore = await Hive.openBox<HomeList>("homelists");
Future insert(String id, HomeList homelist) async {
await _homelistStore.put(id,homelist.toMap());
}
Future update(HomeList homelist) async {
await _homelistStore.put(homelist.id,homelist.toMap());
}
Future delete(HomeList homelist) async {
await _homelistStore.delete(homelist.id);
}
Future<List<HomeList>> getAll() async {
return _homelistStore.values;
}
}
Edit:
I solved this and the final code is:
class HomeListRepository {
Box _homelistStore;
Future<void> insert(String id,HomeList homelist) async {
_homelistStore = await Hive.openBox<HomeList>("homelists");
_homelistStore.put(id,homelist);
}
Future<void> update(HomeList homelist) async {
_homelistStore = await Hive.openBox<HomeList>("homelists");
await _homelistStore.put(homelist.id,homelist);
}
Future<void> delete(HomeList homelist) async {
_homelistStore = await Hive.openBox<HomeList>("homelists");
await _homelistStore.delete(homelist.id);
}
Future<List<HomeList>> readAll() async {
_homelistStore = await Hive.openBox<HomeList>("homelists");
return _homelistStore.values.toList();
}
}
finded on Hive github page:GitHub