如何截取当前widget的截图-Flutter

问题描述 投票:0回答:4

我需要对当前屏幕或小部件进行屏幕截图,并且需要将其写入文件中。

flutter dart screenshot
4个回答
41
投票

我尝试并找到了解决方案,

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/rendering.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static GlobalKey previewContainer = GlobalKey();
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return RepaintBoundary(
        key: previewContainer,
      child: Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: Center(
        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
            ElevatedButton(
                onPressed: takeScreenShot,
              child: const Text('Take a Screenshot'),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    )
    );
  }
  Future<void> takeScreenShot() async{
    final boundary = previewContainer.currentContext!.findRenderObject() as RenderRepaintBoundary;
    final image = await boundary.toImage();
    final directory = (await getApplicationDocumentsDirectory()).path;
    final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    final pngBytes = byteData?.buffer.asUint8List();
    final imgFile =File('$directory/screenshot.png');
    imgFile.writeAsBytes(pngBytes!);
  }
}

最后检查你的应用程序目录你会发现截图.png!!


35
投票

假设您想要截取

FlutterLogo
小部件的屏幕截图。将其包装在
RepaintBoundary
中,将为其子级创建一个单独的显示列表。并提供钥匙

var scr= new GlobalKey();
RepaintBoundary(
         key: scr,
         child: new FlutterLogo(size: 50.0,))

然后你可以通过将边界转换为图像来得到

pngBytes

takescrshot() async {
  RenderRepaintBoundary boundary = scr.currentContext.findRenderObject();
  var image = await boundary.toImage();
  var byteData = await image.toByteData(format: ImageByteFormat.png);
  var pngBytes = byteData.buffer.asUint8List();
  print(pngBytes);
  }

10
投票

这里是flutter 2.0+的解决方法截图分享到社交媒体

 import 'package:flutter/rendering.dart';
        import 'package:flutter/services.dart';
        import 'dart:ui' as ui;
        import 'package:path_provider/path_provider.dart';
        import 'package:share/share.dart';
        
        GlobalKey previewContainer = new GlobalKey();
    
     @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
            title: Text(widget.title),
          ),
          body: RepaintBoundary(
            key: previewContainer,
            child: Center(
              // Center is a layout widget. It takes a single child and positions it
              // in the middle of the parent.
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    'Take Screen Shot',
                  ),
                ],
              ),
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _captureSocialPng,
            tooltip: 'Increment',
            child: Icon(Icons.camera),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    
        
          Future<void> _captureSocialPng() {
            List<String> imagePaths = [];
            final RenderBox box = context.findRenderObject() as RenderBox;
            return new Future.delayed(const Duration(milliseconds: 20), () async {
              RenderRepaintBoundary? boundary = previewContainer.currentContext!
                  .findRenderObject() as RenderRepaintBoundary?;
              ui.Image image = await boundary!.toImage();
              final directory = (await getApplicationDocumentsDirectory()).path;
              ByteData? byteData =
                  await image.toByteData(format: ui.ImageByteFormat.png);
              Uint8List pngBytes = byteData!.buffer.asUint8List();
              File imgFile = new File('$directory/screenshot.png');
              imagePaths.add(imgFile.path);
              imgFile.writeAsBytes(pngBytes).then((value) async {
                await Share.shareFiles(imagePaths,
                    subject: 'Share',
                    text: 'Check this Out!',
                    sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
              }).catchError((onError) {
                print(onError);
              });
            });
          }

2
投票

奔跑

flutter screenshot

它将从您连接的设备中截取屏幕截图并将其保存到您正在进行开发的文件夹中,它将像您的文件夹中那样保存 flutter_01.jpg

© www.soinside.com 2019 - 2024. All rights reserved.