Flutter how to share image on assets folder?

Viewed 1315

With this code I keep getting the error "ENOENT (No such file or directory), null, null, null)". How can I share a file on the assets folder?

Directory directory = await getApplicationDocumentsDirectory();
    Share.shareFiles(['${directory.path}/baws.png'], text: 'Great picture');
3 Answers

First get your image as bytes and copy to temp file.

      final bytes = await rootBundle.load('assets/image.jpg');
      final list = bytes.buffer.asUint8List();

      final tempDir = await getTemporaryDirectory();
      final file = await File('${tempDir.path}/image.jpg').create();
      file.writeAsBytesSync(list);

Then use share package to share it, should work;

Share.shareFiles(['${file.path}'], text: 'Great picture');

The problem you're facing comes from the method getApplicationDocumentsDirectory(); it doesn't give you the right path.

It gives you the path of the hidden directory where the app store data.

You may want to update your code with something like so:

// old code
Share.shareFiles(['${directory.path}/baws.png'], text: 'Great picture');


// new one
Share.shareFiles(['assets/images/baws.png'], text: 'Great picture');

Don't forget to put your 'baws.png' in the folder named assets with a subfolder named image to match the example, and to declare it in your pubspec.yaml

The folder assets need to be at the root of your project directory.

You can find more information on the official documentation here.

                      // import 'package:flutter/services.dart';
                      // import 'package:path_provider/path_provider.dart';
                      // import 'package:share_plus/share_plus.dart';
                      // import 'dart:io'; 
                      // share_plus: any
                      // path_provider: any
shareFile(){
                      ByteData imagebyte = await rootBundle
                          .load('assets/images/kissing_image_real.png');
                      final temp = await getTemporaryDirectory();
                      final path = '${temp.path}/image1.jpg';
                      File(path).writeAsBytesSync(imagebyte.buffer.asUint8List());
                      await Share.shareFiles([path], text: 'Image Shared');

}

Related