Future Completer In Dart
This blog will explore the Future Completer In Dart programming language. We will perceive how to execute a demo program. Learn how to implement and use it in your applications. Which also works for the Flutter framework.
If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.
Table Of Contents::
Introduction:
On the off chance that you’re utilizing Dart or developing a Flutter application, you may currently know about Future. Future is typically used to deal with asynchronous tasks. Obtaining the consequence of a Future is very straightforward.
For instance, on the off chance that we have a capability Future fetchResult(), it’s feasible to obtain the outcome by utilizing the await
keyword.
String result = await fetchResult();
Another alternative is to use a Future
chain.
fetchResult()
.then((value) {
print(value);
});
However, in some cases, it’s impossible to use the methods above to create a Future
. For example, if you need to get the result Future
from a callback function. Let’s take a look at the example below. There is a class MyExectuor
that has a method run
. The class’s constructor has a required callback onDone
. The run
method will call the onDone
method with a value. The objective here is to get the value passed to the onDone
callback.
import 'dart:async';
class MyExecutor {
void Function(String time) onDone;
MyExecutor({
required this.onDone,
});
Future<void> run() async {
await Future.delayed(Duration(seconds: 2));
final DateTime time = DateTime.now();
final String formattedTime = '${time.year}-${time.month}-${time.day} ${time.hour}:${time.minute}:${time.second}';
onDone(formattedTime);
}
}
main() async {
final MyExecutor myExecutor = MyExecutor(
onDone: (String time) async {
// we want to get the value when this callback is invoked
}
);
await myExecutor.run();
}
Since the run technique returns void, and that implies it returns nothing, we can’t get the worth straight by utilizing await.run()
. All things being equal, we need to get the worth inside the passed callback.
Completer:
In the first place, you want to make a Completer by calling its constructor. It has a type parameter where you can characterize the bring type back. The following is an illustration of a Completer that profits a string.final stringCompleter = Completer<String>();
On the off chance that it doesn’t have a return value, you can make a Completer with a void parameter type.
final voidCompleter = Completer<>();
In the event that you don’t determine the type parameter, it will be set as dynamic
.
final dynamicCompleter = Completer(); // Completer<dynamic>
You can likewise utilize a nullable type in the event that the return value can be null.
final nullableStringCompleter = Completer<String?>();
Complete Future:
To finish the Future, you can call the complete
technique with a return value. The value type should be equivalent to the type parameter while making the Completer. Assuming that the sort boundary is void, you don’t have to pass any value. On the off chance that it’s dynamic, you can return a value of any type. You are possibly permitted to return null assuming the sort parameter is void or nullable.void complete([FutureOr<T>? value]);
The following is an illustration of how to finish the Future with a string value.
stringCompleter.complete('foo');
The complete technique must be called once. On the off chance that What’s in store as of now is complete and you call the complete
technique once more, it will throw StateError
.
Complete Future
with Error
A Future can likewise throw an error. With Completer, throwing an error should be possible by calling the completeError technique.
void completeError(Object error, [StackTrace? stackTrace]);
Here is an illustration of how to call the completeError technique
try {
// Do something
} catch (ex, stackTrace) {
stringCompleter.completeError(ex, stackTrace);
}
Get Future
and Value:
Assuming you have a Completer case, you can get to the future property to get the Future that is finished when complete or completeError is called. Assuming you have the Future, you can utilize the await
keyword to return the value by the Future
.
final valueFuture = stringCompleter.future;
final value = await valueFuture;
Get Completion Status:
To get the completion status Representing things to Future
, you can get to the isCompleted property.
final isCompleted = stringCompleter.isCompleted;
Let’s put all the code together:
import 'dart:async';
class MyExecutor {
void Function(String time) onDone;
MyExecutor({
required this.onDone,
});
Future<void> run() async {
await Future.delayed(Duration(seconds: 2));
final DateTime time = DateTime.now();
final String formattedTime =
'${time.year}-${time.month}-${time.day} ${time.hour}:${time.minute}:${time.second}';
onDone(formattedTime);
}
}
main() async {
final stringCompleter = Completer<String>();
final MyExecutor myExecutor = MyExecutor(onDone: (String time) async {
try {
if (time.isNotEmpty) {
stringCompleter.complete(time);
} else {
throw Exception('empty time');
}
} catch (ex, stackTrace) {
stringCompleter.completeError(ex, stackTrace);
}
});
print('isCompleted: ${stringCompleter.isCompleted}');
await myExecutor.run();
print('isCompleted: ${stringCompleter.isCompleted}');
final valueFuture = stringCompleter.future;
final value = await valueFuture;
print('value: $value');
}
When we run the application, we ought to get the screen’s output like the underneath screen Console Output.
isCompleted: false
isCompleted: true
value: 2023-4-7 14:54:11
Process finished with exit code 0
Conclusion:
In the article, I have explained the Future Completer In Dart; you can modify this code according to your choice. This was a small introduction to the Future Completer In Dart User Interaction from my side, and it’s working using Flutter.
Completer can be utilized as a choice to make a Future in Dart/Flutter. The utilization is very basic. If you want to make a Completer, then call the complete or completeError strategy. You can get the Future
of a Completer from the future property. The isCompleted property can be utilized to know whether What’s in Future
has been finished.
I hope this blog will provide you with sufficient information on Trying the Future Completer In Dart of your projects. So please try it.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.