Flutter – I want to display it on the screen right away rather than a file after the screenshot is taken

Issue

By using RepaintBoundary, you can capture only the desired area.

I want to make the screenshot appear right on the screen as soon as you take it.

Solution

You can just store the bytes in a variable, and display it using Image.memory().

Demo:

Press the "Download" button in the middle, to screenshot and display it.

demo

Full source code:

import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey _globalKey = GlobalKey();
  var _bytes;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Screenshot Example")),
      body: Column(
        children: [
          /// Area to be captured
          RepaintBoundary(
            key: _globalKey,
            child: Container(
              width: 300,
              height: 300,
              decoration: BoxDecoration(
                gradient: RadialGradient(
                  colors: [Colors.white, Colors.grey],
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  FlutterLogo(),
                  Text("screenshot me"),
                ],
              ),
            ),
          ),

          /// Button
          IconButton(
            icon: Icon(Icons.file_download),
            onPressed: () async {
              final render = (_globalKey.currentContext!.findRenderObject()
                  as RenderRepaintBoundary);
              final imageBytes = (await (await render.toImage())
                      .toByteData(format: ImageByteFormat.png))!
                  .buffer
                  .asUint8List();
              setState(() {
                _bytes = imageBytes;
              });
            },
          ),

          /// Display
          if (_bytes != null) Image.memory(_bytes, width: 200),
        ],
      ),
    );
  }
}

Answered By – user1032613

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *