Search code examples
imageflutternetwork-programminggame-engineflame

How to load network image in Flame?


In Flame documentation, Image class just load from asset folder.

bgSprite = Sprite('avatar/avatar-sample.png');

How can I load network images in Flame.


Solution

  • You could do something like this in versions after 1.0.0:

    import dart:ui; // This is the package you want the Image class from, there are several
    
    Future<Image> getImage(String path) async {
      Completer<ImageInfo> completer = Completer();
      var img = new NetworkImage(path);
      img.resolve(ImageConfiguration()).addListener(ImageStreamListener((ImageInfo info,bool _){
        completer.complete(info);
      }));
      ImageInfo imageInfo = await completer.future;
      return imageInfo.image;
    }
    

    and then in your onLoad method, just initiate bgSprite:

    @override
    Future<void> onLoad() async {
      final image = await getImage("your-url.com/sample.png");
      bgSprite = Sprite(image);
    }
    

    In 0.28.0, which it looks like you are running, you'll just replace the last line with (but I really recommend upgrading to a version after 1.0.0):

    bgSprite = Sprite.fromImage(image);