ashish rana
ashish rana

Reputation: 327

flutter: Capture screenshot method not working

A button has been, when it is pressed it should be able to take screenshots but the method does not seem to work. The android manifest yml also has the permission for the external storage but once the app loads, it also doesn't ask for the storage permission.

 Center(
                                      child: ElevatedButton(
                                          child:
                                          const Text('Take ScreenShot'),
                                          onPressed: () {
                                            _captureAndSharePng;
                                          }))



 void _captureAndSharePng() async {
    try {
      final RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;
      var image = await boundary.toImage();
      ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();

      final tempDir = await getTemporaryDirectory();
      final file = await io.File('${tempDir.path}/dat.png').create();
      await file.writeAsBytes(pngBytes);
      print(pngBytes);
      print('ares;');

      const channel = MethodChannel('channel:me.alfian.share/share');
      channel.invokeMethod('shareFile', 'dat.png');

    } catch(e) {
      print(e.toString());
    }
  }

Upvotes: 0

Views: 1116

Answers (1)

Sadhik
Sadhik

Reputation: 300

Try this way,

 GlobalKey scr = GlobalKey();

 Future<Uint8List> _capturePng() async {
    RenderRepaintBoundary boundary =
        scr.currentContext!.findRenderObject() as RenderRepaintBoundary;
    var image = await boundary.toImage(pixelRatio: 10);
    var byteData = await image.toByteData(format: ImageByteFormat.png);
    return byteData!.buffer.asUint8List();
  }

  void share_img() async {
    var pngBytes = await _capturePng();
    final directory = (await getApplicationDocumentsDirectory()).path;
    var bs64 = base64Encode(pngBytes);
    print(pngBytes);
    File imgFile = new File('$directory/screenshot.png');
    await imgFile.writeAsBytes(pngBytes);
    Share.shareFiles([imgFile.path], text: '');
    print(bs64);
  }
// use permission_handler to ask for permission
//call function as
if (await Permission.storage.request().isGranted)                                                   {
  share_img();
}

Check this is in your manifest

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Upvotes: 1

Related Questions