This article will show you how to share data from our application to another, just like when you hit share on an image inside your gallery. The system will ask you to select an application to share to.
Watch Video Tutorial
So we are going to achieve this in Flutter with the help of a plugin.
We need to add the plugin to the pubspec.yaml file first.
Add Dependencies
Add this entry below the Dependencies in pubspec.yaml file
dependencies: ... share: ^ 0.6 . 3 + 1 ... |
Now to Invoke the share action with some data we have to call like this…
final RenderBox box = context.findRenderObject(); Share.share(text, subject: subject, sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size); |
Wraps the platform’s native share dialog. Can share a text and/or a URL.
It uses the `ACTION_SEND` Intent on Android and `UIActivityViewController`
on iOS.
The optional [subject] parameter can be used to populate a subject if the
user chooses to send an email.
The optional [sharePositionOrigin] parameter can be used to specify a global
origin rect for the share sheet to popover from on iPads. It has no effect
on non-iPads.
Complete Example
A Complete example will look like this
import 'package:flutter/material.dart' ; import 'package:share/share.dart' ; class ShareDemo extends StatefulWidget { @override ShareDemoState createState() => ShareDemoState(); } class ShareDemoState extends State<ShareDemo> { // String text = '' ; String subject = '' ; share(BuildContext context) { final RenderBox box = context.findRenderObject(); Share.share(text, subject: subject, sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Share Demo' , home: Scaffold( appBar: AppBar( title: const Text( 'Share Demo' ), ), body: Container( padding: EdgeInsets.all( 25.0 ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextField( decoration: const InputDecoration( labelText: 'Text' , hintText: 'Enter some text or link to share' , ), maxLines: 2 , onChanged: (String txt) { setState(() { text = txt; }); }, ), TextField( decoration: const InputDecoration( labelText: 'Text' , hintText: 'Enter some subject to share' , ), maxLines: 2 , onChanged: (String txt) { setState(() { subject = txt; }); }, ), SizedBox( height: 20 , ), Builder( builder: (BuildContext context) { return RaisedButton( child: const Text( 'Share' ), onPressed: text.isEmpty ? null : () { share(context); }, ); }, ), ], ), ), ), ); } } |
That’s it.
Pingback: Google's Flutter Tutorial – Share Data to other applications. | Nikkies Tutorials