Eseguire screenshot in Flutter
In Flutter possiamo eseguire screenshot delle nostre app/widget usando il package screenshot!
È compatibile con tutte le piattaforme; testata su Android e Linux.
In questo articolo vediamo un esempio.
Partiamo dall'installazione:
flutter pub add screenshot
Qui sotto un pò di codice:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:screenshot/screenshot.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final ScreenshotController _screenshotController = ScreenshotController();
@override
void initState() {
super.initState();
}
Future<dynamic> _showCapturedWidget(
BuildContext context, Uint8List capturedImage) {
return showDialog(
useSafeArea: false,
context: context,
builder: (context) => Scaffold(
appBar: AppBar(
title: const Text("Schermata con lo screenshot"),
),
body: Center(
child: Image.memory(capturedImage),
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('Flutter test'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Screenshot(
controller: _screenshotController,
child: Container(
padding: const EdgeInsets.all(30.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.blueAccent, width: 5.0),
color: Colors.amberAccent,
),
child: const Stack(
children: [
Text("Questo è il widget che verrà catturato"),
],
),
),
),
const SizedBox(
height: 25,
),
ElevatedButton(
child: const Text(
'Cattura!',
),
onPressed: () {
_screenshotController
.capture(delay: const Duration(milliseconds: 10))
.then((capturedImage) async {
_showCapturedWidget(context, capturedImage!);
}).catchError((onError) {
print(onError);
});
},
),
],
),
),
);
}
}
Questo eseguirà lo screenshot di un widget e poi lo mostrerà in una schermata a parte.
Enjoy!
dart flutter screenshot
Commentami!