关键在利用RepaintBoundary给Widget转为Image。
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class NewsPage1 extends StatefulWidget {
@override
NewsPage1State createState() => NewsPage1State();
}
class NewsPage1State extends State<NewsPage1> {
// 全局key
final GlobalKey _rootWidgetKey = GlobalKey();
// 图片数组
List<Uint8List> _images = [];
/// 截图
Future<Uint8List?> _capturePng(
GlobalKey globalKey, {
double pixelRatio = 1.0, //截屏的图片与原图的比例
}) async {
try {
RenderRepaintBoundary boundary = globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary;
var image = await boundary.toImage(pixelRatio: pixelRatio);
ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
Uint8List? pngBytes = byteData?.buffer.asUint8List();
return pngBytes;
} catch (e) {
print(e);
}
return null;
}
@override
Widget build(BuildContext context) {
//RepaintBoundary 截屏组件
return RepaintBoundary(
key: _rootWidgetKey,
child: Scaffold(
appBar: AppBar(
title: Text("flutter组件截图"),
),
body: Column(
children: <Widget>[
TextButton(
onPressed: () {
//获取截屏图像
//添加到图片数组中
_capturePng(_rootWidgetKey).then((value) {
if (value != null) {
_images.add(value);
setState(() {});
}
});
},
child: Text("全屏截图"),
),
Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
return Image.memory(
_images[index],
fit: BoxFit.cover,
);
},
itemCount: _images.length,
scrollDirection: Axis.horizontal,
),
)
],
),
),
);
}
}