Sharing Files in Flutter
Sharing is an integral part of mobile apps. Millions of digital content are produced and consumed every minute. Because of this, we can’t avoid a feature like this on our mobile apps.
There is a package named share
in Flutter to do just this.
it can be used to share just text or even Files.
First, let’s add the package to our pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
share: ^2.0.1 # add the latest version from pub.dev
To share a simple text, use Share.share()
anywhere on our App.
Share.share("Your Text to Share");
It will bring up the share dialog of respective platform, whether if you’re using Android or iOs.
If we have to share Files, we can use Share.shareFiles()
it accepts a list of File Paths to share.
File mycoolImage;
Share.shareFiles([mycoolImage.path,]);
below is the same example from Generate Image from Widget Tutorial, but with the added function of sharing the generated Image.
Future<void> takePicture() async {
RenderRepaintBoundary boundary = genKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage();
final directory = (await getApplicationDocumentsDirectory()).path;
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
File imgFile = new File('$directory/photo.png');
await imgFile.writeAsBytes(pngBytes);
await Share.shareFiles([imgFile.path]);//Sharing the generated Image
}
Hope you found something useful here.
I’m always open to suggestions!
Let me know your suggestions and opinions in Twitter DM or drop a mail a [email protected].
If you’re feeling too generous, you can support me through Buy Me a Coffee.
Finally, if you found this helpful, please share this within your reach so that more people can benefit from this. And Follow me on Twitter for getting more posts like these 😉.