Preview widget screenshot flutter - flutter

Hello guys I am new to flutter.
How can I take a screenshot from a widget, preview it to a new page and decide if I would like to save it in the gallery or not?
Here is my code
takeScreenShot(BuildContext context) async {
final path= join((await getTemporaryDirectory()).path,"${DateTime.now()}.png");
RenderRepaintBoundary boundary =
_globalKey.currentContext.findRenderObject();
var image = await boundary.toImage();
var byteData = await image.toByteData(format: ImageByteFormat.png);
var pngBytes = byteData.buffer.asUint8List();
Navigator.push(context, MaterialPageRoute(builder: (builder)=>ScreenshotViewPage(path: path,)));
}
The global key is added to the root widget.

Related

How to create custom QR Codes to launch profile screen in Flutter

I want to have a feature in my Flutter App like Snapcodes on Snapchat. Basically custom “QR” Codes (they aren’t scannable to anything besides Snapchat so not really QR codes) with the app icon in them that launch a users profile when scanned in the app. I can make a simple version of this with plain QR codes using a pub package and Firebase Deeplinking but that isn’t what I want. What I think needs to be done is to create my own “qr” code generator that makes code holding a uid and then a way to decode them when scanned but I have no idea how to do that. Any ideas or pub packages that can do this?
Added for comment:
So I was looking through my old project and I got this ( The Idea of the source code below is that your taking a screenshot programmatically):
import 'dart:ui' as ui; //
final _renderObjectKey = new GlobalKey();
int randomDigit;
Timer _timer;
String userID;
void startTimer() {
//Generate random numbers attached to userID to make qrcode change periodically: improve on this!!!
var range = new Random();
_timer = new Timer.periodic(Duration(seconds: 10), (timer) {
setState(() {
randomDigit = range.nextInt(800) + 100;
});
});
}
#override
void initState() {
super.initState();
userID = auth.currentUser.uid; //if you are using firebaseauth
startTimer();
}
#override
void dispose() {
_timer.cancel();
super.dispose();
}
......
// The widget below is placed inside the body of scaffold
RepaintBoundary(
key: _renderObjectKey,
child:Stack(
alignment: Alignment.center,
children:[
BarcodeWidget(
color: Color(0xFFF9F9F9),
barcode: Barcode.qrCode(
errorCorrectLevel:BarcodeQRCorrectionLevel.high,),
data: '$userID$randomDigit', // this could be uuid
width: height * 0.32, // you can adjust to your liking
height: height * 0.32,
) // BarcodeWidget,
Container( height: 50,width: 50,child:AssetImage('assets/icon.png') // you can do whatever here
])//Stack
)//Repaint boundary
This is where the sauce is:
For android:
void _takePhoto(String _dataString) async {
int randomDigit;
var range = new Random();
randomDigit = range.nextInt(1000000) + 1;
RenderRepaintBoundary boundary =
_renderObjectKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
var pngBytes = byteData.buffer.asUint8List();
final tempDir = await getTemporaryDirectory();
final file =
await new File('${tempDir.path}/image$randomDigit.png').create();
await file.writeAsBytes(pngBytes).then((value) {
GallerySaver.saveImage(value.path, albumName: 'Android Photo album')
.then((bool success) {});
});
}
For Ios:
Future<Uint8List> _getWidgetImage(String _dataString) async {
try {
RenderRepaintBoundary boundary =
_renderObjectKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData byteData =
await image.toByteData(format: ui.ImageByteFormat.png);
var pngBytes = byteData.buffer.asUint8List();
final tempDir = await getTemporaryDirectory();
final file = await new File('${tempDir.path}/image.png').create();
await file.writeAsBytes(pngBytes);
await Share.file(_dataString, '$_dataString.png', pngBytes, 'image/png');
var bs64 = base64Encode(pngBytes);
debugPrint(bs64.length.toString());
return pngBytes;
} catch (exception) {
print(exception);
}
}
Calling the functions:
_takePhoto('$userID$randomDigit');//Android in a textbutton your choice
_getWidgetImage('$userID$randomDigit');//IOS in a textbtuton
keep in mind that I have not been tracking the flutter dependencies I used in this project but I will include them from my pubspec.yaml file:
qr_flutter: ^3.2.0
qrcode: ^1.0.4
barcode: ^1.17.1
share: ^0.6.5+4
gallery_saver: ^2.0.1
path_provider: ^1.6.24
path: ^1.7.0
esys_flutter_share: ^1.0.2
Note: Copy and paste will not work. This will need adjustments.

How to implement twitter share with image file in flutter

I want to implement twitter share in my flutter application.
I convert my widget to image by using RepaintBoundary and stored as ByteData as below.
Future<ByteData> convertWidgetToImage(GlobalKey key) async {
final RenderRepaintBoundary boundary =
key.currentContext!.findRenderObject() as RenderRepaintBoundary;
final image = await boundary.toImage();
final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return byteData!;
}
Then, I want to open twitter app with some default text and with this image data. (I can convert this bytedata to local file path url if needed as below)
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Is there any way I can share this image to twitter (onTap then open twitter app with this image)?
This could be an option but I don't think I can share twitter image
https://pub.dev/packages/social_share

share_plus does not share the text flutter

I am trying to implement sharing widget as a screenshot via share_plus.dart plug in. It works, however it does not attach the string text to the widget. How do I fix that?
Future<void> shareReview() async {
final image = await controller.capture();
saveAndShare(image);
}
void saveAndShare(Uint8List bytes) async {
final directory = await getApplicationDocumentsDirectory();
final image = File('${directory.path}/review.png');
image.writeAsBytesSync(bytes);
final text = 'blahblahblahbalh';
await Share.shareFiles([image.path], text: text);
}

Flutter : How to save widget to png with transparent background?

There is the way to save the widget into transparent png and save it into gallery?
Thanks in advance.
Flutter draws every single pixel, so you can easily convert your widget to an image.
You need to follow these steps:
Edit -- first import path_provider link to pupspec.yaml and then follow this steps
Create a GlobalKey
final _globalKey = GlobalKey();
Create Uint8List
Uint8List pngBytes;
Wrap your widget with RepaintBoundary widget & pass in the key
RepaintBoundary(
key: _globalKey,
child: YourWidget(),
),
Create a method to convert your widget to image:
Future<void> _capturePng() async {
try {
final RenderRepaintBoundary boundary =
_globalKey.currentContext.findRenderObject();
final image = await boundary.toImage(pixelRatio: 2.0); // image quality
final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
pngBytes = byteData.buffer.asUint8List();
} catch (e) {
print(e);
}
}
Convert your image to a file so that you can save it in your app
Future<File> convertImageToFile(Uint8List image) async {
final file = File(
'${(await
getTemporaryDirectory()).path}/${DateTime.now().millisecondsSinceEpoch}.png');
await file.writeAsBytes(image);
return file;
}

Flutter share image - open failed: ENOENT (No such file or directory), null, null)

https://pub.dev/packages/share
Dependency:
share: ^0.6.5+2
Local file directory
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Share function
Future<void> _onShare(BuildContext context) async {
final RenderBox box = context.findRenderObject();
final path = await _localPath;
await Share.shareFiles(
['$path/assets/images/${widget.imgUrl}.png'],
text: text,
sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
}
Button - on press
FlatButton(child: Text('Share'), onPressed: () => _onShare(context)),
I'm using this package to share image from application. I have no issue sharing text but when I add the function to share image, I keep getting errors for missing image.
Am I doing it correctly?
Managed to figure out the problem.
Seems like I need to save image before I can reference the image.
final ByteData bytes = await rootBundle
.load('assets/images/${widget.imgUrl}.png');
final Uint8List list = bytes.buffer.asUint8List();
final directory = (await getExternalStorageDirectory()).path;
File imgFile = File('$directory/screenshot.png');
imgFile.writeAsBytesSync(list);
Share.shareFiles(['$directory/screenshot.png'],
sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);