Flutter社交分享插件social_share的使用

发布于 1周前 作者 ionicwang 来自 Flutter

Flutter社交分享插件social_share的使用

social_share

social_share 插件提供了多种分享选项,可以让你直接分享到某些流行的应用程序或仅通过默认的原生分享功能进行分享。它支持 AndroidiOS 平台,并且可以分享到Instagram故事、Facebook故事以及复制到剪贴板。

配置说明

Android Configuration

修改AndroidManifest.xml

android/app/src/main/AndroidManifest.xml文件中,在<manifest>标签内添加以下属性:

xmlns:tools="http://schemas.android.com/tools"

例如:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="your package...">

然后,在<application>标签内添加以下代码:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.com.shekarmudaliyar.social_share"
    android:exported="false"
    android:grantUriPermissions="true"
    tools:replace="android:authorities">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/filepaths" />
</provider>

创建filepaths.xml

app/src/main/res/xml目录下创建一个名为filepaths.xml的XML文件,并粘贴以下代码:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="image" path="/" />
</paths>

iOS Configuration

Info.plist文件中添加以下内容以启用Instagram和Facebook故事分享:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>instagram-stories</string>
    <string>facebook-stories</string>
    <string>facebook</string>
    <string>instagram</string>
    <string>twitter</string>
    <string>whatsapp</string>
    <string>tg</string>
</array>

如果你要使用Facebook分享功能,则需要在Facebook开发者平台创建应用并获取App ID,然后将其添加到Info.plist中:

<key>FacebookAppID</key>
<string>xxxxxxxxxxxxxxx</string>

使用方法

以下是几种常见的分享方式示例:

Instagram故事分享

SocialShare.shareInstagramStory(imageFile.path, "#ffffff", "#000000", "https://deep-link-url");

Facebook故事分享

对于iOS:

SocialShare.shareFacebookStory(image.path, "#ffffff", "#000000", "https://deep-link-url", "facebook-app-id");

对于Android(需要提供App ID):

SocialShare.shareFacebookStory(image.path, "#ffffff", "#000000", "https://deep-link-url", "facebook-app-id", appId: "xxxxxxxxxxxxx");

复制到剪贴板

SocialShare.copyToClipboard("This is Social Share plugin");

Twitter分享

// 不带话题
SocialShare.shareTwitter("This is Social Share plugin");

// 带话题
SocialShare.shareTwitter("This is Social Share twitter example", hashtags: ["hello", "world", "foo", "bar"]);

// 带话题和链接
SocialShare.shareTwitter("This is Social Share twitter example", hashtags: ["hello", "world", "foo", "bar"], url: "https://your-url-here/");

SMS分享

// 不带链接的消息
SocialShare.shareSms("This is Social Share Sms example");

// 带链接的消息
SocialShare.shareSms("This is Social Share Sms example", url: "https://your-url-here/");

WhatsApp分享

SocialShare.shareWhatsapp("Hello World");

Telegram分享

SocialShare.shareTelegram("Hello World");

默认分享选项

// 不带图片
SocialShare.shareOptions("Hello world");

// 带图片
SocialShare.shareOptions("Hello world", imagePath: image.path);

检查已安装的应用

SocialShare.checkInstalledAppsForShare();

示例Demo

下面是一个完整的Flutter项目示例,展示了如何使用social_share插件进行各种类型的分享操作。

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:screenshot/screenshot.dart';
import 'package:social_share/social_share.dart';

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

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

class _MyAppState extends State<MyApp> {
  String facebookId = "xxxxxxxx";

  var imageBackground = "image-background.jpg";
  var videoBackground = "video-background.mp4";
  String imageBackgroundPath = "";
  String videoBackgroundPath = "";

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

  Future<void> copyBundleAssets() async {
    imageBackgroundPath = await copyImage(imageBackground);
    videoBackgroundPath = await copyImage(videoBackground);
  }

  Future<String> copyImage(String filename) async {
    final tempDir = await getTemporaryDirectory();
    ByteData bytes = await rootBundle.load("assets/$filename");
    final assetPath = '${tempDir.path}/$filename';
    File file = await File(assetPath).create();
    await file.writeAsBytes(bytes.buffer.asUint8List());
    return file.path;
  }

  Future<String?> pickImage() async {
    final file = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (file == null) {
      return null;
    }
    return file.path;
  }

  Future<String?> screenshot() async {
    var data = await screenshotController.capture();
    if (data == null) {
      return null;
    }
    final tempDir = await getTemporaryDirectory();
    final assetPath = '${tempDir.path}/temp.png';
    File file = await File(assetPath).create();
    await file.writeAsBytes(data);
    return file.path;
  }

  ScreenshotController screenshotController = ScreenshotController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Social Share'),
        ),
        body: Screenshot(
          controller: screenshotController,
          child: Container(
            color: Colors.white,
            alignment: Alignment.center,
            child: Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "Instagram",
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                      SizedBox(width: 40),
                      ElevatedButton(
                        child: Icon(Icons.gradient),
                        onPressed: () async {
                          var path = await pickImage();
                          if (path == null) {
                            return;
                          }
                          SocialShare.shareInstagramStory(
                            appId: facebookId,
                            imagePath: path,
                            backgroundTopColor: "#ffffff",
                            backgroundBottomColor: "#000000",
                          ).then((data) {
                            print(data);
                          });
                        },
                      ),
                      SizedBox(width: 20),
                      ElevatedButton(
                        child: Icon(Icons.image),
                        onPressed: () async {
                          var path = await pickImage();
                          if (path == null) {
                            return;
                          }
                          SocialShare.shareInstagramStory(
                            appId: facebookId,
                            imagePath: path,
                            backgroundResourcePath: imageBackgroundPath,
                          ).then((data) {
                            print(data);
                          });
                        },
                      ),
                      SizedBox(width: 20),
                      ElevatedButton(
                        child: Icon(Icons.videocam),
                        onPressed: () async {
                          var path = await screenshot();
                          if (path == null) {
                            return;
                          }
                          SocialShare.shareInstagramStory(
                            appId: facebookId,
                            imagePath: path,
                            backgroundResourcePath: videoBackgroundPath,
                          ).then((data) {
                            print(data);
                          });
                        },
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "Facebook",
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                      SizedBox(width: 40),
                      ElevatedButton(
                        child: Icon(Icons.gradient),
                        onPressed: () async {
                          var path = await pickImage();
                          if (path == null) {
                            return;
                          }
                          SocialShare.shareFacebookStory(
                            appId: facebookId,
                            imagePath: path,
                            backgroundTopColor: "#ffffff",
                            backgroundBottomColor: "#000000",
                          ).then((data) {
                            print(data);
                          });
                        },
                      ),
                      SizedBox(width: 20),
                      ElevatedButton(
                        child: Icon(Icons.image),
                        onPressed: () async {
                          var path = await pickImage();
                          if (path == null) {
                            return;
                          }
                          SocialShare.shareFacebookStory(
                            appId: facebookId,
                            imagePath: path,
                            backgroundResourcePath: imageBackgroundPath,
                          ).then((data) {
                            print(data);
                          });
                        },
                      ),
                      SizedBox(width: 20),
                      ElevatedButton(
                        child: Icon(Icons.videocam),
                        onPressed: () async {
                          var path = await screenshot();
                          if (path == null) {
                            return;
                          }
                          await SocialShare.shareFacebookStory(
                            appId: facebookId,
                            imagePath: path,
                            backgroundResourcePath: videoBackgroundPath,
                          ).then((data) {
                            print(data);
                          });
                        },
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "Twitter",
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                      SizedBox(width: 40),
                      ElevatedButton(
                        child: Icon(Icons.text_fields),
                        onPressed: () async {
                          SocialShare.shareTwitter(
                            "This is Social Share twitter example with link.  ",
                            hashtags: ["SocialSharePlugin", "world", "foo", "bar"],
                            url: "https://google.com/hello",
                            trailingText: "cool!!",
                          ).then((data) {
                            print(data);
                          });
                        },
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "Clipboard",
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                      SizedBox(width: 40),
                      ElevatedButton(
                        child: Icon(Icons.image),
                        onPressed: () async {
                          SocialShare.copyToClipboard(
                            image: await screenshot(),
                          ).then((data) {
                            print(data);
                          });
                        },
                      ),
                      SizedBox(width: 20),
                      ElevatedButton(
                        child: Icon(Icons.text_fields),
                        onPressed: () async {
                          SocialShare.copyToClipboard(
                            text: "This is Social Share plugin",
                          ).then((data) {
                            print(data);
                          });
                        },
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "SMS",
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                      SizedBox(width: 40),
                      ElevatedButton(
                        child: Icon(Icons.text_fields),
                        onPressed: () async {
                          SocialShare.shareSms(
                            "This is Social Share Sms example",
                            url: "https://google.com/",
                            trailingText: "\nhello",
                          ).then((data) {
                            print(data);
                          });
                        },
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "Share Options",
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                      SizedBox(width: 40),
                      ElevatedButton(
                        child: Icon(Icons.text_fields),
                        onPressed: () async {
                          SocialShare.shareOptions("Hello world").then((data) {
                            print(data);
                          });
                        },
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "Whatsapp",
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                      SizedBox(width: 40),
                      ElevatedButton(
                        onPressed: () async {
                          SocialShare.shareWhatsapp(
                            "Hello World \n https://google.com",
                          ).then((data) {
                            print(data);
                          });
                        },
                        child: Icon(Icons.text_fields),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "Telegram",
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                      SizedBox(width: 40),
                      ElevatedButton(
                        onPressed: () async {
                          SocialShare.shareTelegram(
                            "Hello World \n https://google.com",
                          ).then((data) {
                            print(data);
                          });
                        },
                        child: Icon(Icons.text_fields),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "Get all Apps",
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                      SizedBox(width: 40),
                      ElevatedButton(
                        child: Icon(Icons.text_fields),
                        onPressed: () async {
                          SocialShare.checkInstalledAppsForShare().then((data) {
                            print(data.toString());
                          });
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

这个示例展示了如何配置和使用social_share插件来实现不同类型的社交分享功能。你可以根据自己的需求修改和扩展这些代码片段。


更多关于Flutter社交分享插件social_share的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter社交分享插件social_share的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用social_share插件来实现社交分享的示例代码。social_share插件允许你将文本、图片或文件分享到不同的社交平台,如微信、微博、QQ等。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加social_share插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  social_share: ^4.0.3  # 请检查最新版本号

然后运行flutter pub get来安装依赖。

2. 导入插件

在你的Dart文件中导入social_share插件:

import 'package:social_share/social_share.dart';

3. 使用插件

下面是一个简单的示例,展示如何分享文本和图片:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Social Share Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: () {
                  _shareText();
                },
                child: Text('Share Text'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  _shareImage();
                },
                child: Text('Share Image'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _shareText() async {
    String shareText = "Hello, I am sharing this text!";
    try {
      await SocialShare.shareText(shareText);
      print("Text shared successfully!");
    } catch (e) {
      print("Failed to share text: $e");
    }
  }

  void _shareImage() async {
    String imagePath = "assets/images/sample.png";  // 确保你的assets文件夹中有这张图片
    ByteData imageData = await rootBundle.load(imagePath);
    Uint8List bytes = imageData.buffer.asUint8List();
    try {
      await SocialShare.shareImage(bytes, imageUrl: null, mimeType: "image/png");
      print("Image shared successfully!");
    } catch (e) {
      print("Failed to share image: $e");
    }
  }
}

注意事项

  1. 图片资源:在上面的代码中,imagePath指向的是assets文件夹中的图片。确保你已经在pubspec.yaml中声明了这些资源:

    flutter:
      assets:
        - assets/images/sample.png
    
  2. 权限:某些社交平台可能需要特定的权限,例如读写存储权限。确保你的应用已经请求并获得了这些权限。

  3. 平台特定配置social_share插件可能需要在iOS和Android平台上进行特定的配置。请参考插件的官方文档以获取更多信息。

通过上述代码,你可以在Flutter应用中实现基本的文本和图片分享功能。如果需要更高级的功能,如分享文件或自定义分享内容,请参考social_share插件的官方文档。

回到顶部