Flutter how to share image on assets folder?
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.
Andrejcc
Updated on December 30, 2022Comments
-
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 over 2 yearsThe 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 over 2 yearsThis 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 over 2 yearsNo problem happy to solve it. Could you please share the full error message?
-
Andrejcc over 2 yearsIt is fixed! Thank you, have a great day :)
-
Muhtar over 2 yearsCheers mate :) !
-
Abhishek Kumar over 2 years@Muhtar
getTemporaryDirectory()
showing me error. Is there any special thing toimport
that I am missing? -
Abhishek Kumar over 2 yearsOkay, now I found the package Path Provider (pub.dev/packages/path_provider) that solved the issue.