Flutter - 我想在屏幕截图后立即显示在屏幕上而不是文件

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

通过使用 RepaintBoundary,您可以只捕获所需的区域。

我想让截图在你截取后立即出现在屏幕上。

您可以只将字节存储在一个变量中,然后使用 Image.memory() 显示它。

演示:

点击中间的“下载”按钮,进行截图显示。

完整源代码:

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),
        ],
      ),
    );
  }
}