Flutter Share Data to Another Application

CodeWithFlutter
3 Min Read

Sharing data from one application to another application is the most essential feature in the application. To implement sharing feature in your application, we need a package called a share. Let’s get started.

Creating Project

First, create a project by using IDE. If you are using other text editors, then use the flutter create command. If you are using an existing project skip this step.

Adding Package

Open your pubspec.yaml file, then add the share: ^2.0.1 package under your dependency section. Then run flutter pub get command. If you are using android studio click pub get or if you are using visual studio code then simply save your project.

Implementing Share Plugin

In this tutorial, I am using a simple example. If you are using other projects just understand the implementation technique and use your own.

Import the share library,

import 'package:share/share.dart';

Create a function called _shareData(). The underscore indicates it is a private function. Make it private or public as per your need.

Then, import the static share method. For example,

_shareData(){
Share.share('check out my website https://codewithflutter.com');
}

The subject of the share method is optional, if you need a subject, then add the subject. The subject is mainly used when you are sharing data to email.

_shareData(){
Share.share('check out my website https://codewithflutter.com', subject: 'Look what I made!');
}

To share one or multiple files invoke the static shareFiles method that accepts multiple files. If you need text and subject you can put it. Text and Subject are totally optional. For Example,

_shareData(){
Share.shareFiles(['${directory.path}/image.jpg'], text: 'Great picture');
Share.shareFiles(['${directory.path}/image1.jpg', '${directory.path}/image2.jpg']);
}

Don’t forget to call the _shareData() function.

Flutter Share Data to Another Application Example Full Code

import 'package:flutter/material.dart';
import 'package:share/share.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  _shareData() {
    Share.share('check out my website https://www.codewithflutter.com');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Share Data - Demo"),
      ),
      body: Center(
          child: MaterialButton(
        color: Colors.blue,
        onPressed: () {
          _shareData();
        },
        child: Text(
          "Click to share",
        ),
      )),
    );
  }
}

Output Of the Code,

I hope this article will help you. Thank you.

Share this Article
Leave a comment