How to add a Share button to your Flutter app

Updated: March 23, 2023 By: A Goodman Post a comment

This article shows you how to implement a share button to share content from your Flutter app via the platform’s share dialog by using a plugin called share_plus. The share dialog may contain SMS, Messenger, Facebook, Email, Twitter, AirDrop, Telegram… based on the user’s settings.

Installation

1. You can conveniently add share_plus and its version to the dependencies section in your pubspec.yaml file by executing the following command:

flutter pub add share_plus

2. After that, run:

flutter pub get

3. Import the plugin into your Dart code:

import 'package:share_plus/share_plus.dart';

Simple Usage

Share text or URLs:

Share.share('Some text');

You can share multiple images or files at once like so:

Share.shareFiles([
'${directory.path}/image1.jpg',
/* ... */
'${directory.path}/image(n).jpg'
]);

For more clarity, please see the example below.

Complete Example

Preview

This tiny sample app has a share button that lets the user share some text. Here’s how it works:

The code

// main.dart
import 'package:flutter/material.dart';
import 'package:share_plus/share_plus.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  final String _content =
      'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum diam ipsum, lobortis quis ultricies non, lacinia at justo.';

  void _shareContent() {
    Share.share(_content);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Center(
          child: Column(children: [
            Text(_content),
            const SizedBox(height: 15),
            ElevatedButton.icon(
                onPressed: _shareContent,
                icon: const Icon(Icons.share),
                label: const Text('Share This Sentence'))
          ]),
        ),
      ),
    );
  }
}

Conclusion

You’ve learned how to share content from a Flutter app by making use of the share_plus package. This technique is helpful if you want your app to get more installs at no cost. Continue exploring more new and amazing things about Flutter by taking a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles