flutter对某一个Widget进行截图保存

学习笔记 yekong

保存图片需要获取文件存储权限
引入插件permission_handler(权限控制插件)、image_gallery_saver(文件保存插件)

pubspec.yaml文件中引入:

image_gallery_saver: ^1.2.2 #图片保存到本地

 

IOS端添加权限

ios/Runner/Info.plist

<key>NSPhotoLibraryAddUsageDescription</key>
<string>请允许APP保存图片到相册</string>

Android配置
app/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

 

import 'dart:ui' as ui;
import 'package:image_gallery_saver/image_gallery_saver.dart';
  GlobalKey globalKey = GlobalKey();
RepaintBoundary(
        key: globalKey,
        child: SingleChildScrollView(
            child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(
                    top: 0.0, left: 0.0, right: 0.0, bottom: 0.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    qiehuan(),
                    zonghebiaoti(),
                  ],
                ))),
      )
GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () async{
                    BuildContext buildContext = globalKey.currentContext;
                    if (null != buildContext){
                      RenderRepaintBoundary boundary = buildContext.findRenderObject();
                      ui.Image image = await boundary.toImage();
                      ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
                      final result = await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
                      Fluttertoast.showToast(
                        msg: '已保存到相册',
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.CENTER,
                      );
                    }
                  },
                  child: Image(
                    image: AssetImage("images/icon_down1.png"),
                    width: ScreenUtil.getInstance().setWidth(22),
                    height: ScreenUtil.getInstance().setWidth(28),
                  ),
                ),

 

 

喜欢