Completer and Future in dart? Completer and Future in dart? dart dart

Completer and Future in dart?


The Future object that is returned by that method is, in a sense, connected to that completer object, which will complete at some point "in the future". The .complete() method is called on the Completer, which signals the future that it is complete. Here's a more simplified example:

Future<String> someFutureResult(){   final c = new Completer();   // complete will be called in 3 seconds by the timer.   new Timer(3000, (_) => c.complete("you should see me second"));   return c.future;}main(){   someFutureResult().then((String result) => print('$result'));   print("you should see me first");}

Here's a link to a blog post which details other scenarios where futures are helpful


The Completer is used to provide a value to a future and signal it to fire any remaining callbacks and continuations that are attached to the future (i.e. at the call-site / in user code).

The completer.complete(null) is what's used to signal to the future that the async operation has completed. The API for complete shows that it must supply 1 argument (i.e. not optional).

void complete(T value)

This code is not interested in returning a value, just notifying the call-site that the operation is complete. As it just prints, you will need to check the console for the output.


Correct answer has errors in DartPad, the reason could be Dart version.

error : The argument type 'int' can't be assigned to the parameter type 'Duration'.error : The argument type '(dynamic) → void' can't be assigned to the parameter type '() → void'.

The following snippet is complement

import 'dart:async';Future<dynamic> someFutureResult(){   final c = new Completer();   // complete will be called in 3 seconds by the timer.   new Timer(Duration(seconds: 3), () {            print("Yeah, this line is printed after 3 seconds");       c.complete("you should see me final");          });   return c.future;}main(){   someFutureResult().then((dynamic result) => print('$result'));   print("you should see me first");}

reslut

you should see me firstYeah, this line is printed after 3 secondsyou should see me final