Search code examples
flutterflame

How to Capture a screenshot and share using flutter


Is it possible to take a screenshot of the screen using flame and flutter? So when the user clicks a button, it will share the screenshot with anyone he chooses to share it to.


Solution

  • Since you are specifically using flame, you are in luck! Flame renders your game on the canvas. Your game render method takes a canvas and draws a frame of your game.

    Normally the canvas provided is the device screen, but can easily call the render method yourself with a different canvas, say, an image.

        final PictureRecorder recorder = PictureRecorder();
        final Rect rect = Rect.fromLTWH(0.0, 0.0, game.size.width, game.size.height);
        final Canvas c = Canvas(recorder, rect);
    
        game.render(c);
    
        final image = await recorder.endRecording().toImage(game.size.width, game.size.height);
    

    Then you can save that image on, let's say, a file, or in memory.

    Now note that this will render only your game, and will render the exact frame you are in when you call this. But I assume that is what you want since you specifically tagged this question with flame. There might be better ways of screenshooting with Flutter in general, but using flame, this is the best way.