Skip to content

Instantly share code, notes, and snippets.

@bambinoua
Created October 4, 2022 06:09
Show Gist options
  • Save bambinoua/1c2c2d4086049b743f88235f61ccd294 to your computer and use it in GitHub Desktop.
Save bambinoua/1c2c2d4086049b743f88235f61ccd294 to your computer and use it in GitHub Desktop.
Makes a snhapshot of widget
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Web Snapshot Bug',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final repaintBoundaryKey = GlobalKey();
final snapshot = ValueNotifier(Uint8List(0));
@override
void dispose() {
snapshot.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
snapshot.value = await _makeSnapshot();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: RepaintBoundary(
key: repaintBoundaryKey,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const ElevatedButton(
onPressed: null,
child: Text('Press to make a snapshot'),
),
const SizedBox(height: 50),
ValueListenableBuilder<Uint8List>(
valueListenable: snapshot,
builder: (context, data, child) {
if (data.isNotEmpty) {
return Image.memory(
data,
width: 500,
height: 500,
);
}
return const Center(child: CircularProgressIndicator());
},
),
],
),
),
),
);
}
Future<Uint8List> _makeSnapshot() async {
final repaintBoundary = repaintBoundaryKey.currentContext!
.findRenderObject() as RenderRepaintBoundary;
final image = await repaintBoundary.toImage();
final byteData = await image.toByteData(format: ImageByteFormat.png);
return byteData!.buffer.asUint8List();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment