Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Future.then() with async/await

I've always considered async/await more elegant/sexy over the Futures API, but now I'm faced with a situation where the Future API implementation is very short and concise and the async/await alternative seems verbose and ugly.

I marked my two question #1 and #2 in the comments:

class ItemsRepository
{
  Future<dynamic> item_int2string;

  ItemsRepository() {
    // #1
    item_int2string = 
     rootBundle.loadString('assets/data/item_int2string.json').then(jsonDecode);
  }

  Future<String> getItem(String id) async {
    // #2
    return await item_int2string[id];
  }
}

#1: How do I use async/await here instead of Future.then()? What's the most elegant solution?

#2: Is this efficient if the method is called a lot? How much overhead does await add? Should I make the resolved future an instance variable, aka

completedFuture ??= await item_int2string;
return completedFuture[id];
like image 938
deekay42 Avatar asked Mar 06 '26 18:03

deekay42


1 Answers

1: How do I use async/await here instead of Future.then()? What's the most elegant solution?

async methods are contagious. That means your ItemsRepository method has to be async in order to use await inside. This also means you have to call it asynchronously from other places. See example:

Future<dynamic> ItemsRepository() async {
    // #1
    myString = await rootBundle.loadString('assets/data/item_int2string.json');
    // do something with my string here, which is not in a Future anymore...
  }

Note that using .then is absolutely the same as await in a async function. It is just syntactic sugar. Note that you would use .then differently than in your example though:

  ItemsRepository() {
    // #1
    
     rootBundle.loadString('assets/data/item_int2string.json').then((String myString) {
       // do something with myString here, which is not in a Future anymore...
     });
  }

And for #2 don't worry about a performance impact of async code. The code will be executed at the same speed as synchronous code, just later whenever the callback happens. The only reason async exists is for having an easy way of allowing code to continue running while the system waits for the return of the asynchronously called portion. For example not block the UI while waiting for the disk to load a file.

I recommend you read the basic docs about async in Dart.

like image 182
Oswin Noetzelmann Avatar answered Mar 08 '26 12:03

Oswin Noetzelmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!