Sharing Files In Flutter

Use Share Package To share files In Flutter Apps

Shaiq khan
Sep 9, 2020 · 6 min read

Flutter is an incredible new technology for cross-platform development beyond question. By and large, you will pull off standard highlights. Eventually, it would help if you had some platform-specific functionality. That is when Platform Channels prove to be useful.

In this article, we will explore Sharing Files In Flutter. We will also implement a demo the sharing files feature using the share package in your flutter applications.

Table Of Contents :

Flutter

Sharing Files

Implementation

Code Implement

Code File

Conclusion

Flutter :

Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time.

  • To begin with, you’ll need the necessary information on Flutter, Git, and GitHub. If you are new to flutter, you can get started by reading the official documentation on flutter.dev

Sharing Files :

We will be capturing the current screen and sharing that screenshot on a single tap, and other we will convert the image URL to an image file and share it with a single tap.

We’ll use a modified version of the share package for sharing files. And about the already available packages, we have few issues with these packages like we cannot share a File which we call from a network.

Demo module ::

On this screen, we will create two buttons in your app, which will call the above two logics and do our work.

Implementation :

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:

path_provider: ^1.6.11
http: ^0.12.0+4
google_fonts: ^1.1.0

Step 2: Add Assets :

Add assets to pubspec — yaml file.

We will add images in the assets folder

assets:
- assets/

Step 3: Import

import 'package:http/http.dart';
import 'package:path_provider/path_provider.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:share/share.dart';
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

Step 4: Run flutter packages get in the root directory of your app.

Step 5: We will now create a static Global key.

static GlobalKey _globalKey = GlobalKey();

Step 6: Enable AndriodX

Add this to your gradle. properties file:

org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called home_page.dart inside the lib folder.

On this home page, we will create two buttons for sharing files. The first one is Share Screenshot and the others one is URL FIle Share.

Let’s declare the Share ScreenShot function:

Future<Null> shareScreenshot() async {
setState(() {
button1 = true;
});
try {
RenderRepaintBoundary boundary =
_globalKey.currentContext.findRenderObject();
if (boundary.debugNeedsPaint) {
Timer(Duration(seconds: 1), () => shareScreenshot());
return null;
}
ui.Image image = await boundary.toImage();
final directory = (await getExternalStorageDirectory()).path;
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
File imgFile = new File('$directory/screenshot.png');
imgFile.writeAsBytes(pngBytes);
final RenderBox box = context.findRenderObject();
Share.shareFile(File('$directory/screenshot.png'),
subject: 'Share ScreenShot',
text: 'Hello, check your share files!',
sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size
);
} on PlatformException catch (e) {
print("Exception while taking screenshot:" + e.toString());
}
setState(() {
button1 = false;
});
}

We will catch the current screen, save it as an image file in the device, and afterward Share that file by giving its directory path. You have to wrap your Scaffold widget with RepaintBoundary as a parent and give a key to it since it makes a different presentation list for its child.

  • We have to get the storage location path to save the image, for that we are utilizing the path_provider bundle.
  • At that point, we are changing over the image into a byte exhibit and giving an arrangement of the image(in our case, we have .png). What’s more, later, we are converting over the above bytes into Uint8List, and afterward composing it in the imgFile.

If you are unable to take a screenshot you can add the below code in the method.

if (boundary.debugNeedsPaint) {
Timer(Duration(seconds: 1), () => shareScreenshot());
return null;
}

We are currently sharing the imgFile utilizing Share.shareFile by giving the area of storage. This component can be utilized to share reports, information, or charts as screen capture.

Let’s declare the URL FIle Share function:

Future<Null> urlFileShare() async {
setState(() {
button2 = true;
});
final RenderBox box = context.findRenderObject();
if (Platform.isAndroid) {
var url = 'https://i.ytimg.com/vi/fq4N0hgOWzU/maxresdefault.jpg';
var response = await get(url);
final documentDirectory = (await getExternalStorageDirectory()).path;
File imgFile = new File('$documentDirectory/flutter.png');
imgFile.writeAsBytesSync(response.bodyBytes);
Share.shareFile(File('$documentDirectory/flutter.png'),
subject: 'URL File Share',
text: 'Hello, check your share files!',
sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
} else {
Share.share('Hello, check your share files!',
subject: 'URL File Share',
sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
}
setState(() {
button2 = false;
});
}

In this method, we will get and convert the image from a URL to an image file, save it in the device, and then share it as we did it earlier. Also, in this method, the Http package is required.

  • In this method, we have an image URL, and we are utilizing the getting strategy to store it in a variable, and afterward continuing with similar steps as in the past.
  • We are composing response.bodyBytes as bytes.
  • We are offering the file to the Share.shareFile().

This element can be utilized to share images from an API call, such as sharing an individual item picture with a share button/symbol.

Code File:

Conclusion :

In the article, I have explained the basic demo of Sharing Files. You can modify this code according to your choice, and this was a small basic introduction of Sharing Files from my side and its working using Flutter.

I hope this blog will provide you with sufficient information in Trying up Sharing Files in Flutter in your flutter projects. This is a demo example show two ways to share your file. The first one is sharing the current screenshot, and others convert the image URL to an image file and then share, So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

find the source code of the Flutter Sharing Files Demo:

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high…