Search code examples
dartdart-async

Can I call a non-async function asynchronously in Dart?


I want to decode a gif with the image package using DecodeGifAnimation, but it takes too long and causes my webapp to freeze. The library also doesn't seem to have any async methods. I looked up how to do asynchronous processing in Dart, and it seems that I need to use Futures, although I'm not sure how to create one for my function.

Not really sure what I'm doing

void decode(Uint8List data) {
  Future anim = decodeGifAnimation(data); // but it returns Animation, not a Future!
  anim.then(prepare);
}

Solution

  • void decode(Uint8List data) {
      new Future(() => decodeGifAnimation(data)).then(prepeare);
    }
    

    or

    Future decode(Uint8List data) {
      return new Future(() => decodeGifAnimation(data)).then(prepeare);
    }
    

    if you want to do some async processing when the method returns to call the method like

    decode(data).then(xxx);