首页 > 解决方案 > Flutter - 我想在屏幕截图后立即将其显示在屏幕上而不是文件上

问题描述

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

我想让屏幕截图在您拍摄后立即出现在屏幕上。

标签: flutterflutter-layoutflutter-test

解决方案


您可以将字节存储在变量中,并使用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),
        ],
      ),
    );
  }
}

推荐阅读