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.
Table of Contents
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:
- How to implement Star Rating in Flutter
- Flutter: Creating a Custom Number Stepper Input
- How to Create a Countdown Timer in Flutter
- How to get user’s current location in Flutter
- How to implement an image picker in Flutter
- Flutter: Showing a badge on the Top Right of a widget
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.