概述
Flutter生成图片相当于是对某一个Widget进行截图保存
保存图片需要获取文件存储权限
引入插件permission_handler(权限控制插件)、image_gallery_saver(文件保存插件)设置修改权限文件
引入插件后,需要对ios和安卓分别设置权限
安卓修改文件android/app/src/main/AndroidManifest.xml
,添加如下代码
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
ios修改文件ios/Runner/Info.plist
,添加如下代码
<key>NSPhotoLibraryAddUsageDescription</key>
<string>请允许APP保存图片到相册</string>
3.flutter代码中使用
GlobalKey globalKey = GlobalKey();
........
RepaintBoundary(
key: globalKey,
child: Container(
...........
),
)
//触发保存
onTap: () async {
//检查是否有存储权限
var status = await Permission.storage.status;
if (!status.isGranted) {
status = await Permission.storage.request();
print(status);
return;
}
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());
MessageToast.succ(context, '海报已保存到相册');
}
Navigator.of(context).pop();
},