Flutter社交分享插件social_share_plus的使用

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

Flutter社交分享插件social_share_plus的使用

功能

本插件支持多种分享内容和分享平台。可能是最简单的分享工具。

支持的平台和内容

平台 内容 操作系统
微信 文本/图片/音乐/视频/网页/文件 Android/iOS
Facebook 文本/图片/网页/文件 Android/iOS
Line 文本/图片/文件 Android/iOS
Twitter 文本/图片/文件 Android/iOS
WhatsApp 文本/图片/文件 Android/iOS
系统分享

使用说明

iOS配置

在Info.plist文件中添加以下内容:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fb</string>
    <string>fbauth</string>
    <string>weixin</string>
    <string>weixinULAPI</string>
    <string>fbapi20150629</string>
    <string>fbapi20160328</string>
    <string>fbapi20130214</string>
    <string>fbapi</string>
    <string>fb-messenger-share-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
    <string>twitter</string>
    <string>whatsapp</string>
    <string>line</string>
</array>

注册平台

仅需要配置微信平台。appIdsecretKey 来自于 WechatOpenPlatform。其他平台无需配置。

ShareRegister register = ShareRegister();
register.setupWechat(appId, secretKey, universalLink); // 只需要配置微信
SharePlugin.registerPlatforms(register);

开始分享

生成分享参数对象:

Future<ShareParamsBean> generateBean(SharePlatform platform) async {
  var response = await Dio().get(imageUrl, options: Options(responseType: ResponseType.bytes));
  File file = await createFileOfPdfUrl(Uint8List.fromList(response.data));

  return ShareParamsBean(
    contentType: LaShareContentTypes.image,
    platform: platform,
    imageFilePath: file.path,
    pkgNameAndroid: "com.example.yourapp",
  );
}

分享内容:

final PlatformCallback _notInstallCallback = (int? platformId) {
  BotToast.showText(text: "未安装应用");
};

final Function _successCallback = () {
  BotToast.showText(text: "分享成功");
};

final Function _errorCallback = (String code, {String? message}) {
  BotToast.showText(text: "分享失败:$code");
};

// 分享图片到微信好友
SharePlugin.share(
  await generateBean(SharePlatforms.wechatSession),
  _notInstallCallback,
  _successCallback,
  _errorCallback,
);

// 分享网页到微信好友
SharePlugin.share(
  await generateBean(SharePlatforms.wechatSession),
  _notInstallCallback,
  _successCallback,
  _errorCallback,
);

检查是否安装了应用:

SharePlugin.isClientInstalled(SharePlatforms.whatsApp);

预览

注意事项

  1. iOS微信图片分享使用系统分享,因为微信禁止国外公司直接分享图片。
  2. 你需要添加一些scheme配置以便访问外部应用程序。参考示例配置。

示例代码

以下是完整的示例代码:

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:social_share_plus/social_share.dart';

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final String _imageUrl =
      'https://images.ctfassets.net/41derkrb00ei/56TMtTb175hK9WydTsxkbN/bc9081f8bacca79faed82f1755c5c8a3/_______________1-0118______.png';
  final String _webpageUrl = "https://www.baidu.com/";
  final String _imageUrlForWeb =
      "https://cdn.lingoace.com/image/pub/default-avatar-st.jpg";

  [@override](/user/override)
  void initState() {
    super.initState();
    _registerPlatform();
  }

  void _registerPlatform() {
    ShareRegister register = ShareRegister();
    register.setupWechat(
        "wx66192691ae27148b", "https://pplingo.page.link/UdTB/");
    SharePlugin.registerPlatforms(register);
  }

  final PlatformCallback _notInstallCallback = (int? platformId) {
    BotToast.showText(text: "未安装应用");
  };

  final Function _successCallback = () {
    BotToast.showText(text: "分享成功");
  };

  final Function _errorCallback = (String code, {String? message}) {
    BotToast.showText(text: "分享失败:$code");
  };

  Future<ShareParamsBean> _buildImageBean(SharePlatform platform,
      {String? pkgName}) async {
    var response = await Dio()
        .get(_imageUrl, options: Options(responseType: ResponseType.bytes));
    File file = await createFileOfPdfUrl(Uint8List.fromList(response.data));
    return ShareParamsBean(
      contentType: LaShareContentTypes.image,
      platform: platform,
      imageFilePath: file.path,
      pkgNameAndroid: pkgName,
    );
  }

  Future<ShareParamsBean> _buildWebpageBean(SharePlatform platform,
      {String? pkgName}) async {
    var response = await Dio().get(_imageUrlForWeb,
        options: Options(responseType: ResponseType.bytes));
    File file = await createFileOfPdfUrl(Uint8List.fromList(response.data));
    return ShareParamsBean(
      contentType: LaShareContentTypes.webpage,
      platform: platform,
      imageFilePath: file.path,
      webUrl: _webpageUrl,
      title: "这是标题",
      text: "这是描述",
      pkgNameAndroid: pkgName,
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    final botToastBuilder = BotToastInit(); // 1. 调用BotToastInit
    return MaterialApp(
      builder: (context, child) {
        return botToastBuilder(context, child);
      },
      home: Builder(builder: (BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('插件示例应用'),
          ),
          body: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                MaterialButton(
                  child: const Text("分享图片到微信好友"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildImageBean(SharePlatforms.wechatSession),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享图片到微信朋友圈"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildImageBean(SharePlatforms.wechatTimeline),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享图片到Facebook"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildImageBean(SharePlatforms.facebook),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享图片到WhatsApp"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildImageBean(SharePlatforms.whatsApp),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享图片到Twitter"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildImageBean(SharePlatforms.twitter),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享图片到Line"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildImageBean(SharePlatforms.line),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享图片到系统分享"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildImageBean(SharePlatforms.native),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享网页到微信好友"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildWebpageBean(SharePlatforms.wechatSession),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享网页到微信朋友圈"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildWebpageBean(SharePlatforms.wechatTimeline),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享网页到Facebook"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildWebpageBean(SharePlatforms.facebook),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享网页到WhatsApp"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildWebpageBean(SharePlatforms.whatsApp),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享网页到Twitter"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildWebpageBean(SharePlatforms.twitter),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享网页到Line"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildWebpageBean(SharePlatforms.line),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
                MaterialButton(
                  child: const Text("分享网页到系统分享"),
                  onPressed: () async {
                    SharePlugin.share(
                        await _buildWebpageBean(SharePlatforms.native),
                        _notInstallCallback,
                        _successCallback,
                        _errorCallback);
                  },
                ),
              ],
            ),
          ),
        );
      }),
    );
  }

  static Future<File> writeToFile(var data, String path) async {
    final buffer = data.buffer;
    return File(path).writeAsBytes(
        buffer.asUint8List(data.offsetInBytes, data.lengthInBytes),
        flush: true);
  }

  static Future<File> createFileOfPdfUrl(var bytes) async {
    var dir = (await getTemporaryDirectory()).path + "/imageShare";
    Directory directory = Directory(dir);
    if (!directory.existsSync()) {
      directory.createSync();
    }
    String filePath = "${DateTime.now().millisecondsSinceEpoch}.jpg";

    File file = await writeToFile(bytes, '$dir/$filePath');
    return file;
  }
}

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

1 回复

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


当然,以下是如何在Flutter应用中使用social_share_plus插件进行社交分享的示例代码。

首先,确保你已经在pubspec.yaml文件中添加了social_share_plus依赖:

dependencies:
  flutter:
    sdk: flutter
  social_share_plus: ^3.0.0  # 请检查最新版本号

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

接下来,在你的Flutter项目中,你可以按照以下步骤使用social_share_plus插件:

  1. 导入插件

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

import 'package:social_share_plus/social_share_plus.dart';
  1. 分享文本

以下是一个分享文本的示例:

void shareText() async {
  final RenderBox box = context.findRenderObject();
  await Share.share(
    '这是一个分享的文本内容!',
    sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size,
  );
}

你可以将shareText函数绑定到一个按钮点击事件上,例如:

ElevatedButton(
  onPressed: shareText,
  child: Text('分享文本'),
),
  1. 分享带有URL的文本

如果你想要分享带有URL的文本,可以这样做:

void shareTextWithUrl() async {
  final RenderBox box = context.findRenderObject();
  await Share.share(
    '这是一个分享的文本内容,点击这里查看更多:https://www.example.com',
    sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size,
  );
}

同样,你可以将shareTextWithUrl函数绑定到一个按钮点击事件上:

ElevatedButton(
  onPressed: shareTextWithUrl,
  child: Text('分享带有URL的文本'),
),
  1. 分享图片

分享图片的示例代码如下:

void shareImage(BuildContext context) async {
  final ByteData imageBytes = await rootBundle.load('assets/images/share_image.png');
  final Uint8List uint8list = imageBytes.buffer.asUint8List();

  final RenderBox box = context.findRenderObject();
  await Share.shareFiles(
    [ShareFile(bytes: uint8list, mimeType: 'image/png')],
    text: '分享一张图片!',
    sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size,
  );
}

注意,你需要确保在pubspec.yaml文件中添加了图片资源:

flutter:
  assets:
    - assets/images/share_image.png

同样,将shareImage函数绑定到一个按钮点击事件上:

ElevatedButton(
  onPressed: () => shareImage(context),
  child: Text('分享图片'),
),
  1. 处理分享结果(可选)

如果你需要处理分享结果(例如,分享是否成功),你可以使用Share.shareFilesShare.share的返回值。这些函数返回一个Future<ShareResult?>,你可以根据需要对它进行处理:

void shareTextWithResult() async {
  final RenderBox box = context.findRenderObject();
  final ShareResult? result = await Share.share(
    '这是一个分享的文本内容!',
    sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size,
  );

  if (result != null) {
    if (result.completed) {
      print('分享成功!');
    } else {
      print('分享失败!');
    }
  }
}

shareTextWithResult函数绑定到一个按钮点击事件上:

ElevatedButton(
  onPressed: shareTextWithResult,
  child: Text('分享文本并处理结果'),
),

以上就是在Flutter中使用social_share_plus插件进行社交分享的一些示例代码。根据你的需求,你可以进一步自定义和扩展这些功能。

回到顶部