Shruti Ramnandan Sharma
Shruti Ramnandan Sharma

Reputation: 4565

share link on social media via several buttons in android and ios with flutter

These are three social media buttons. I just want to share a link on social media via these buttons in Android as well as ios.

enter image description here

I used flutter_share_me plugin. but there are two problems with this plugin.

1.)This plugin is defined for only Android devices, not for ios.

2.)it isn't defined for Instagram.

CODE:

For Facebook:

IconButton(
             icon: Image.asset("assets/icons/facebook_logo.png",fit:BoxFit.fill,color: Colors.white,),
             onPressed: (){
                 FlutterShareMe().shareToFacebbok(url: appUrl,  msg: "Babilok");

               }     
             ),

For Twitter:

IconButton(
             icon: Image.asset("assets/icons/twitter_logo1.png",fit:BoxFit.fill,color: Colors.white,),
             onPressed: (){
                 FlutterShareMe().shareToTwitter(url: appUrl,  msg: "Babilok");

               }     
             ),

For Instagram:

IconButton(
             icon: Image.asset("assets/icons/instagram_logo.png",fit:BoxFit.fill,color: Colors.white,),
             onPressed: (){
                ?????????.....

               }     
             ),

Upvotes: 2

Views: 14333

Answers (3)

Bhagyashree Khatri
Bhagyashree Khatri

Reputation: 31

You can use this plugin flutter_social_content_share

This plugin works fine both on iOS & Android as well.

/// SHARE ON FACEBOOK CALL
  shareOnFacebook() async {
    String result = await FlutterSocialContentShare.share(
        type: ShareType.facebookWithoutImage,
        url: "https://www.apple.com",
        quote: "captions");
    print(result);
  }

  /// SHARE ON INSTAGRAM CALL
  shareOnInstagram() async {
    String result = await FlutterSocialContentShare.share(
        type: ShareType.instagramWithImageUrl,
        imageUrl:
            "https://post.healthline.com/wp-content/uploads/2020/09/healthy-eating-ingredients-732x549-thumbnail-732x549.jpg");
    print(result);
  }

  /// SHARE ON WHATSAPP CALL
  shareWatsapp() async {
    String result = await FlutterSocialContentShare.shareOnWhatsapp(
        number: "xxxxxx", text: "Text appears here");
    print(result);
  }

  /// SHARE ON EMAIL CALL
  shareEmail() async {
    String result = await FlutterSocialContentShare.shareOnEmail(
        recipients: ["[email protected]"],
        subject: "Subject appears here",
        body: "Body appears here",
        isHTML: true); //default isHTML: False
    print(result);
  }

  /// SHARE ON SMS CALL
  shareSMS() async {
    String result = await FlutterSocialContentShare.shareOnSMS(
        recipients: ["xxxxxx"], text: "Text appears here");
    print(result);
  }

  ///Build Context
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: <Widget>[
            Text('Running on: $_platformVersion\n'),
            RaisedButton(
              child: Text("Share to facebook button"),
              color: Colors.red,
              onPressed: () {
                shareOnFacebook();
              },
            ),
            RaisedButton(
              child: Text("Share to instagram button"),
              color: Colors.red,
              onPressed: () {
                shareOnInstagram();
              },
            ),
            RaisedButton(
              child: Text("Share to whatsapp button"),
              color: Colors.red,
              onPressed: () {
                shareWatsapp();
              },
            ),
            RaisedButton(
              child: Text("Share to email button"),
              color: Colors.red,
              onPressed: () {
                shareEmail();
              },
            ),
            RaisedButton(
              child: Text("Share to sms button"),
              color: Colors.red,
              onPressed: () {
                shareSMS();
              },
            ),
          ],
        ),
      ),
    );
  }

Upvotes: 3

You can use pack Share social media plugin

final twitterLogin = new ShareSocialMediaPlugin(
  consumerKey: "consumerKey",
  consumerSecret: 'consumerSecret');

         RaisedButton(
                    child: Text(titleTwitterButton, style: TextStyle(fontSize: 20)),
                    onPressed: () async {
                    //Platform in Android
                      if (Platform.isAndroid) {
                        var result = await twitterLogin.shareTwitter("conectado desde plugin");
                        print(result);
                        if(result != null){
                          if (result == "success"){
                            print("success!");
                          }else{
                            print("fail");
                          }
                        }
                      }
                      //Platform in iOS
                      else if (Platform.isIOS) {
                        var sessionTwitter = await twitterLogin.currentSessionIOS();
                        var tweet = await twitterLogin.shareTwitteriOS(
                            sessionTwitter["outhToken"],
                            sessionTwitter["oauthTokenSecret"],
                            "test cpmplete future",
                            twitterLogin.consumerKey,
                            twitterLogin.consumerSecret);

                        final response = json.decode(tweet.body);
                        if (response['text'] != null) {
                           print("success");
                        }else{
                          print("fail");
                        }
                      }
                    },
                  ),

That plugin have support for instagram, twitter, line

Upvotes: 0

chunhunghan
chunhunghan

Reputation: 54397

You can use package https://pub.dev/packages/social_share_plugin
package description forget to mention include twitter now

full example code

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:social_share_plugin/social_share_plugin.dart';
import 'package:image_picker/image_picker.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await SocialSharePlugin.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: <Widget>[
            Center(
              child: Text('Running on: $_platformVersion\n'),
            ),
            RaisedButton(
              child: Text('Share to Instagram'),
              onPressed: () async {
                File file = await ImagePicker.pickImage(source: ImageSource.gallery);
                await SocialSharePlugin.shareToFeedInstagram("image/*", file.path);
              },
            ),
            RaisedButton(
              child: Text('Share to Facebook'),
              onPressed: () async {
                File file = await ImagePicker.pickImage(source: ImageSource.gallery);
                await SocialSharePlugin.shareToFeedFacebook('test', file.path);
              },
            ),
            RaisedButton(
              child: Text('Share to Facebook Link'),
              onPressed: () async {
                String url = 'https://flutter.dev/';
                final quote =
                    'Flutter is Google’s portable UI toolkit for building beautiful, natively-compiled applications for mobile, web, and desktop from a single codebase.';
                final result = await SocialSharePlugin.shareToFeedFacebookLink(
                  quote: quote,
                  url: url,
                  onSuccess: (postId) {
                    print('FACEBOOK SUCCESS $postId');
                    return;
                  },
                  onCancel: () {
                    print('FACEBOOK CANCELLED');
                    return;
                  },
                  onError: (error) {
                    print('FACEBOOK ERROR $error');
                    return;
                  },
                );

                print(result);
              },
            ),
            RaisedButton(
              child: Text('Share to Twitter'),
              onPressed: () async {
                String url = 'https://flutter.dev/';
                final text =
                    'Flutter is Google’s portable UI toolkit for building beautiful, natively-compiled applications for mobile, web, and desktop from a single codebase.';
                final result = await SocialSharePlugin.shareToTwitter(
                    text: text,
                    url: url,
                    onSuccess: (_) {
                      print('TWITTER SUCCESS');
                      return;
                    },
                    onCancel: () {
                      print('TWITTER CANCELLED');
                      return;
                    });
                print(result);
              },
            ),
          ],
        ),
      ),
    );
  }
}

enter image description here

Upvotes: 1

Related Questions