Dart: Turn Callback Functions into a Futures! 2018, Flutter!!

Brian Schardt
2 min readJul 11, 2018

--

I never thought it would come to this! What you ask? That I would be learning the language dart, after investing so much time and energy into perfecting coding in javascript.

However, after AirBNB just announced they are moving away from react native with some really good reasons, I decided to try Google’s hybrid solution, Flutter. You can read their post here.

Flutter uses the language Dart which is like a mix of javascript and C++.

In Dart they support asynchronous style of programming with callbacks, and what they call “Futures”. Futures are basically(not exactly) what promises are in javascript. They allow for sudo synchronous style of coding while maintaining asynchronous functionality using async/await syntax.

Something that was not obvious from reading documentation was how to convert a callback in Dart to a Future. In javascript, we would use promisify or do something like this. Yes this is not ideal but from maintaining consistency of code to use promises this is necessary.

Javascript — convert callback to Promise

function timeout(time){
return new Promise(resolve=>{
setTimeout(()=>{
resolve('done with timeout');
}, time)
});
}

I was wondering, how do you in Dart convert a call back to a Future(Promise). This is how:

Dart — convert callback to Future

Future time(int time) async {

Completer c = new Completer();
new Timer(new Duration(seconds: time), (){
c.complete('done with time out');
});

return c.future;
}

If you have any other questions let me know! I try to respond within the hour!

— Brian Alois(Schardt)

--

--