Flutter how to share image on assets folder?

943

Solution 1

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');

Solution 2

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.

Share:
943
Andrejcc
Author by

Andrejcc

Updated on December 30, 2022

Comments

  • Andrejcc
    Andrejcc 10 months

    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');
    
  • Andrejcc
    Andrejcc over 2 years
    The asset works when adding an ImageAsset widget, but doesn't work with the code you sent me. I did all that and it still gives me assets/images/baws.png: open failed: ENOENT (No such file or directory)
  • Andrejcc
    Andrejcc over 2 years
    This worked! Omg thank you! I have been at this for many days :(. Now it says direct share not available. If you happen to know where I can search to find the issue it would be much appreciated. If not, thank you so much anyway!
  • Muhtar
    Muhtar over 2 years
    No problem happy to solve it. Could you please share the full error message?
  • Andrejcc
    Andrejcc over 2 years
    It is fixed! Thank you, have a great day :)
  • Muhtar
    Muhtar over 2 years
    Cheers mate :) !
  • Abhishek Kumar
    Abhishek Kumar over 2 years
    @Muhtar getTemporaryDirectory() showing me error. Is there any special thing to import that I am missing?
  • Abhishek Kumar
    Abhishek Kumar over 2 years
    Okay, now I found the package Path Provider (pub.dev/packages/path_provider) that solved the issue.