Flutter社交分享插件lecle_social_share的使用
Flutter社交分享插件lecle_social_share的使用
插件简介
lecle_social_share
是一个Flutter项目,支持将文件分享到社交媒体(如Facebook、Instagram等)。如果你只想在某些平台上分享文件,这个插件非常适合你。
支持的平台:
- Messenger
- Telegram
- TikTok
这些平台可以通过 LecleSocialShare
类中的静态实例来表示:
- F: Facebook
- I: Instagram
- M: Messenger
- T: Telegram
- W: WhatsApp
- TW: Twitter
- TI: TikTok
要使用该插件,只需调用 LecleSocialShare
类中对应平台的实例,并调用相应的分享方法即可。
Android配置
修改 AndroidManifest.xml
-
添加命名空间:
xmlns:tools="http://schemas.android.com/tools"
-
在
<manifest>
标签内添加权限和查询:<queries> <!-- 显式声明的应用程序 --> <package android:name="com.instagram.android" /> <package android:name="com.facebook.katana" /> <package android:name="com.facebook.orca" /> <package android:name="org.telegram.messenger" /> <package android:name="com.whatsapp" /> <package android:name="com.twitter.android" /> <package android:name="com.zhiliaoapp.musically" /> <package android:name="com.ss.android.ugc.trill" /> </queries> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" />
-
创建
provider_paths_app.xml
文件并添加路径配置:<?xml version="1.0" encoding="utf-8"?> <paths> <external-path name="external_files" path="." /> </paths>
-
将文件提供者添加到
AndroidManifest.xml
中:<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.[your_custom_fileProvider_path]" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/[your_custom_fileProvider_file_name]" /> </provider>
Facebook应用注册
- 在
/android/app/src/main/values
文件夹中创建strings.xml
文件,并添加你的Facebook App ID和Client Token。 - 获取Facebook Client Token:访问 Meta for Developers,进入设置 -> 高级 -> 安全 -> 应用代码。
- 获取Facebook App ID:进入设置 -> 基本信息 -> App ID。
- 添加以下XML标签到
AndroidManifest.xml
:<provider android:name="com.facebook.FacebookContentProvider" android:authorities="com.facebook.app.FacebookContentProvider[your_facebook_app_id]" android:exported="true" /> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="[@string](/user/string)/facebook_app_id" /> <meta-data android:name="com.facebook.sdk.ClientToken" android:value="[@string](/user/string)/facebook_client_token" /> <activity android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:theme="@style/[your_custom_theme]" /> <activity android:name="com.facebook.CustomTabMainActivity" /> <activity android:name="com.facebook.CustomTabActivity" android:exported="true" tools:node="merge"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="fbconnect" android:host="cct.${applicationId}" /> </intent-filter> </activity>
iOS配置
修改 Info.plist
- 设置最低部署版本为iOS 11。
- 添加以下内容到
Info.plist
文件:<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>fb[your_facebook_app_id]</string> <string>[your_tiktok_app_id]</string> </array> </dict> </array> <key>LSApplicationQueriesSchemes</key> <array> <string>instagram</string> <string>fb</string> <string>fbauth2</string> <string>fbshareextension</string> <string>fbapi</string> <string>facebook-reels</string> <string>facebook-stories</string> <string>fb-messenger-share-api</string> <string>fb-messenger</string> <string>tg</string> <string>whatsapp</string> <string>twitter</string> <string>tiktokopensdk</string> <string>tiktoksharesdk</string> <string>snssdk1180</string> <string>snssdk1233</string> </array> <key>NSPhotoLibraryUsageDescription</key> <string>$(PRODUCT_NAME) needs permission to access photos and videos on your device</string> <key>NSMicrophoneUsageDescription</key> <string>$(PRODUCT_NAME) does not require access to the microphone.</string> <key>NSCameraUsageDescription</key> <string>$(PRODUCT_NAME) requires access to the camera.</string> <key>NSAppleMusicUsageDescription</key> <string>$(PRODUCT_NAME) requires access to play music</string> <key>FacebookAppID</key> <string>[your_facebook_app_id]</string> <key>FacebookClientToken</key> <string>[your_facebook_client_token]</string> <key>FacebookDisplayName</key> <string>[your_facebook_app_display_name]</string> <key>NSBonjourServices</key> <array> <string>_dartobservatory._tcp</string> </array> <key>TikTokAppID</key> <string>[your_tiktok_app_id]</string>
修改 AppDelegate.swift
更新 AppDelegate.swift
文件以注册Facebook和TikTok:
import UIKit
import Flutter
import FBSDKCoreKit
import TikTokOpenSDK
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
FBSDKCoreKit.ApplicationDelegate.shared.application(
application,
didFinishLaunchingWithOptions: launchOptions
)
TikTokOpenSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
guard let sourceApplication = options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
let annotation = options[UIApplication.OpenURLOptionsKey.annotation] else {
return false
}
if TikTokOpenSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: sourceApplication, annotation: annotation) {
return true
}
return false
}
override func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
if TikTokOpenSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) {
return true
}
return false
}
override func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
if TikTokOpenSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: nil, annotation: "") {
return true
}
return false
}
}
示例代码
以下是一个完整的示例代码,展示了如何使用 lecle_social_share
插件进行不同平台的分享:
import 'dart:async';
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:lecle_social_share/lecle_social_share.dart';
import 'package:lecle_social_share/models/models.dart';
void main() {
runApp(
const MaterialApp(
home: MyApp(),
debugShowCheckedModeBanner: false,
),
);
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<String?>? videoUrls = [];
List<String?>? imageUrls = [];
final _picker = ImagePicker();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Social Media share plugin example'),
centerTitle: true,
),
body: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
physics: const ClampingScrollPhysics(),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Padding(
padding: EdgeInsets.only(top: 24.0, bottom: 8.0),
child: Text(
'Basic share',
style: TextStyle(fontSize: 20.0),
),
),
ElevatedButton(
onPressed: () async {
var video =
await _picker.pickVideo(source: ImageSource.gallery);
if (video != null) {
LecleSocialShare.F.shareFileToFacebook(
filePath: video.path,
dstPath: '/LecleSocialShareExample/Facebook/',
fileProviderPath: '.social.share.fileprovider',
fileType: AssetType.video,
);
}
},
child: const Text('Share file to facebook'),
),
ElevatedButton(
onPressed: () {
LecleSocialShare.F.shareFeedContentToFacebook(
link: "https://pub.dev",
linkName: "pub",
hashtag: "flutter_pub",
);
},
child: const Text('Share feed content to facebook'),
),
ElevatedButton(
onPressed: () {
LecleSocialShare.F.shareLinkContentToFacebook(
contentUrl: "https://pub.dev",
);
},
child: const Text('Share link content to facebook'),
),
ElevatedButton(
onPressed: () async {
var texture =
await _picker.pickImage(source: ImageSource.gallery);
if (texture != null) {
LecleSocialShare.F.shareCameraEffectToFacebook(
cameraEffectTextures: CameraEffectTextures(
textureKey: 'texture_key',
textureUrl: texture.path,
),
cameraEffectArguments: const CameraEffectArguments(
argumentKey: 'argument_key',
argumentValue: 'argument_value',
argumentList: [],
),
hashtag: '#helloworld',
contentUrl: 'https://pub.dev',
);
}
},
child: const Text('Share camera effect to facebook'),
),
const Padding(
padding: EdgeInsets.only(top: 24.0, bottom: 8.0),
child: Text(
'Media content share',
style: TextStyle(fontSize: 20.0),
),
),
ElevatedButton(
onPressed: () async {
imageUrls = (await _picker.pickMultiImage())
?.map((image) => image.path)
.toList();
videoUrls =
(await _pickFile(FileType.video, allowMultiple: true))
?.paths;
LecleSocialShare.F.shareMediaContentFileToFacebook(
imageUrls: imageUrls,
videoUrls: videoUrls,
fileProviderPath: '.social.share.fileprovider',
);
},
child: const Text('Share media content file to facebook'),
),
const Padding(
padding: EdgeInsets.only(top: 24.0, bottom: 8.0),
child: Text(
'Facebook story share',
style: TextStyle(fontSize: 20.0),
),
),
ElevatedButton(
onPressed: () async {
var image =
await _picker.pickImage(source: ImageSource.gallery);
LecleSocialShare.F.shareBackgroundAssetFileToFacebookStory(
appId: '3258588111079263',
filePath: image?.path,
fileProviderPath: '.social.share.fileprovider',
fileType: AssetType.image,
);
},
child: const Text(
'Share background asset file to facebook story',
),
),
ElevatedButton(
onPressed: () async {
var image =
await _picker.pickImage(source: ImageSource.gallery);
LecleSocialShare.F.shareStickerAssetToFacebookStory(
appId: '3258588111079263',
stickerPath: image?.path,
fileProviderPath: '.social.share.fileprovider',
);
},
child: const Text(
'Share sticker background asset to facebook story'),
),
Padding(
padding: const EdgeInsets.only(top: 24.0, bottom: 8.0),
child: Text(
'Facebook story share ${Platform.isAndroid ? 'using ShareStoryContent' : ''}',
style: const TextStyle(fontSize: 20.0),
),
),
Visibility(
visible: Platform.isAndroid,
child: ElevatedButton(
onPressed: () async {
var image =
await _picker.pickImage(source: ImageSource.gallery);
LecleSocialShare.F
.shareBitmapImageBackgroundAssetToFacebookStory(
imagePath: image?.path,
fileProviderPath: '.social.share.fileprovider',
);
},
child: const Text(
'Share bitmap image background asset to facebook story'),
),
),
Visibility(
visible: Platform.isAndroid,
child: ElevatedButton(
onPressed: () async {
var image =
await _picker.pickImage(source: ImageSource.gallery);
LecleSocialShare.F
.shareImageBackgroundAssetContentToFacebookStory(
photoBackgroundAssetPath: image?.path,
fileProviderPath: '.social.share.fileprovider',
);
},
child: const Text(
'Share photo background asset content to facebook story'),
),
),
Visibility(
visible: Platform.isAndroid,
child: ElevatedButton(
onPressed: () async {
var video =
await _picker.pickVideo(source: ImageSource.gallery);
LecleSocialShare.F
.shareVideoBackgroundAssetContentToFacebookStory(
videoBackgroundAssetPath: video?.path,
fileProviderPath: '.social.share.fileprovider',
);
},
child: const Text(
'Share video background asset to facebook story'),
),
),
Visibility(
visible: Platform.isIOS,
child: ElevatedButton(
onPressed: () async {
var images = await _picker.pickMultiImage();
var stickers = await _picker.pickMultiImage();
LecleSocialShare.F
.shareBackgroundImageAndStickerToFacebookStoryiOS(
photoBackgroundAssetPaths:
images?.map((image) => image.path).toList(),
stickerAssetPaths:
stickers?.map((image) => image.path).toList(),
appId: '3258588111079263',
);
},
child: const Text(
'Share background image and sticker asset to facebook story iOS'),
),
),
const Padding(
padding: EdgeInsets.only(top: 24.0, bottom: 8.0),
child: Text(
'Facebook reels share',
style: TextStyle(fontSize: 20.0),
),
),
ElevatedButton(
onPressed: () async {
XFile? sticker;
if (Platform.isAndroid) {
sticker =
await _picker.pickImage(source: ImageSource.gallery);
}
var video = await _pickFile(FileType.video);
LecleSocialShare.F.shareVideoToFacebookReels(
filePath: video?.paths[0],
fileProviderPath: '.social.share.fileprovider',
appId: '3258588111079263',
stickerPath: sticker?.path,
);
},
child: const Text(
'Share video asset (and sticker on Android) to facebook reels'),
),
const Padding(
padding: EdgeInsets.only(top: 24.0, bottom: 8.0),
child: Text(
'Instagram share',
style: TextStyle(fontSize: 20.0),
),
),
ElevatedButton(
onPressed: () async {
var video =
await _picker.pickImage(source: ImageSource.gallery);
if (video != null) {
LecleSocialShare.I.shareFileToInstagram(
filePath: video.path,
fileProviderPath: '.social.share.fileprovider',
fileType: AssetType.image,
);
}
},
child: const Text('Share file to instagram'),
),
ElevatedButton(
onPressed: () async {
LecleSocialShare.I.sendMessageToInstagram(
message: 'Hello world',
);
},
child: const Text('Send message to instagram'),
),
const Padding(
padding: EdgeInsets.only(top: 24.0, bottom: 8.0),
child: Text(
'Messenger share',
style: TextStyle(fontSize: 20.0),
),
),
ElevatedButton(
onPressed: () async {
var video =
await _picker.pickVideo(source: ImageSource.gallery);
LecleSocialShare.M
.shareFileToMessenger(
filePath: video?.path,
fileProviderPath: '.social.share.fileprovider',
fileType: AssetType.video,
hashtag: '#helloworld',
contentUrl: 'https://pub.dev',
)
.catchError((err) {
print('Share file to messenger error $err');
});
},
child: const Text('Share file to messenger'),
),
ElevatedButton(
onPressed: () async {
LecleSocialShare.M.sendMessageToMessenger(
message: 'https://pub.dev',
quote: 'Hello world',
hashtag: '#hello',
);
},
child: const Text('Send message to messenger'),
),
ElevatedButton(
onPressed: () async {
LecleSocialShare.M.shareLinkContentToMessenger(
contentUrl: 'https://pub.dev',
quote: 'Hello world',
hashtag: '#hello',
);
},
child: const Text('Share link content to messenger'),
),
const Padding(
padding: EdgeInsets.only(top: 24.0, bottom: 8.0),
child: Text(
'Telegram share',
style: TextStyle(fontSize: 20.0),
),
),
ElevatedButton(
onPressed: () async {
LecleSocialShare.T.sendMessageToTelegram(
message: 'Hello world',
);
},
child: const Text('Send message to Telegram'),
),
ElevatedButton(
onPressed: () async {
LecleSocialShare.T.openTelegramDirectMessage(
username: 'user_name',
);
},
child: const Text('Open Telegram direct message'),
),
ElevatedButton(
onPressed: () async {
LecleSocialShare.T.openTelegramChannelViaShareLink(
inviteLink: 'your_invite_link',
);
},
child: const Text('Open Telegram group via invite link'),
),
ElevatedButton(
onPressed: () async {
var file = await _pickFile(FileType.any);
LecleSocialShare.T.shareFileToTelegram(
filePath: file?.paths[0],
fileProviderPath: '.social.share.fileprovider',
fileType: AssetType.any,
message: 'Hello friend',
);
},
child: const Text('Share file to Telegram'),
),
const Padding(
padding: EdgeInsets.only(top: 24.0, bottom: 8.0),
child: Text(
'WhatsApp share',
style: TextStyle(fontSize: 20.0),
),
),
ElevatedButton(
onPressed: () async {
var file = await _pickFile(FileType.any);
LecleSocialShare.W.shareFileToWhatsApp(
filePath: file?.paths[0],
fileType: AssetType.pdf,
fileProviderPath: '.social.share.fileprovider',
message: 'Hello friend',
);
},
child: const Text('Share file to WhatsApp'),
),
ElevatedButton(
onPressed: () async {
LecleSocialShare.W.sendMessageToWhatsApp(
message: 'https://pub.dev',
phoneNumber: "receiver_phone_number",
);
},
child: const Text('Send message to WhatsApp'),
),
const Padding(
padding: EdgeInsets.only(top: 24.0, bottom: 8.0),
child: Text(
'Twitter share',
style: TextStyle(fontSize: 20.0),
),
),
ElevatedButton(
onPressed: () async {
LecleSocialShare.TW.createTwitterTweet(
title: 'Hello world',
attachedUrl: "https://pub.dev",
hashtags: [
'hello',
'world',
],
via: 'abc',
related: ['twitter', 'twitterapi'],
);
},
child: const Text('Create Twitter tweet'),
),
ElevatedButton(
onPressed: () async {
var file =
await _picker.pickImage(source: ImageSource.gallery);
LecleSocialShare.TW.shareFileToTwitter(
filePath: file?.path,
fileProviderPath: '.social.share.fileprovider',
fileType: AssetType.image,
iOSConsumerKey: 'abc',
iOSSecretKey: 'xyz',
title: "Hello world",
);
},
child: const Text('Share file to Twitter'),
),
const Padding(
padding: EdgeInsets.only(top: 24.0, bottom: 8.0),
child: Text(
'TikTok share',
style: TextStyle(fontSize: 20.0),
),
),
ElevatedButton(
onPressed: () async {
var res = await _picker.pickMultiImage();
LecleSocialShare.TI.shareFilesToTikTok(
fileUrls: res?.map((e) => e.path).toList(),
fileType: AssetType.image,
fileProviderPath: '.social.share.fileprovider',
);
},
child: const Text('Share files to TikTok'),
),
ElevatedButton(
onPressed: () async {
LecleSocialShare.TI.openTikTokUserPage(
username: 'username',
);
},
child: const Text('Open TikTok user page'),
),
const SizedBox(height: 24.0),
],
),
),
),
);
}
Future<FilePickerResult?> _pickFile(FileType type,
{bool allowMultiple = false}) async {
return await FilePicker.platform
.pickFiles(allowMultiple: allowMultiple, type: type);
}
}
通过以上步骤和示例代码,你可以轻松地在Flutter应用中集成 lecle_social_share
插件,并实现与多个社交平台的分享功能。
更多关于Flutter社交分享插件lecle_social_share的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter社交分享插件lecle_social_share的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中使用lecle_social_share
插件进行社交分享的示例代码。这个插件支持多种社交平台,如微信、QQ、微博等。
首先,你需要在你的pubspec.yaml
文件中添加lecle_social_share
依赖:
dependencies:
flutter:
sdk: flutter
lecle_social_share: ^最新版本号 # 请替换为最新的版本号
然后运行flutter pub get
来获取依赖。
接下来,在你的Flutter项目中导入lecle_social_share
包:
import 'package:lecle_social_share/lecle_social_share.dart';
下面是一个简单的例子,展示了如何使用lecle_social_share
插件来分享文本和图片:
import 'package:flutter/material.dart';
import 'package:lecle_social_share/lecle_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'),
),
],
),
),
),
);
}
Future<void> _shareText() async {
try {
final ShareResult result = await LecleSocialShare.share(
text: 'Hello, I am sharing some text!',
title: 'Share Text',
platform: SharePlatform.all, // 可以指定具体的平台,如SharePlatform.weixin, SharePlatform.qq等
);
print('Share result: $result');
} catch (e) {
print('Error sharing text: $e');
}
}
Future<void> _shareImage() async {
try {
final ShareResult result = await LecleSocialShare.share(
imageUrl: 'https://example.com/path/to/your/image.jpg', // 替换为实际的图片URL
title: 'Share Image',
platform: SharePlatform.all, // 可以指定具体的平台
);
print('Share result: $result');
} catch (e) {
print('Error sharing image: $e');
}
}
}
在这个示例中,我们创建了一个简单的Flutter应用,其中包含两个按钮:一个用于分享文本,另一个用于分享图片。_shareText
和_shareImage
函数分别处理这两种分享类型。
_shareText
函数使用LecleSocialShare.share
方法分享文本。_shareImage
函数同样使用LecleSocialShare.share
方法,但这次是指定了一个图片的URL。
请注意,实际使用时,你可能需要根据具体平台的要求处理权限问题(例如,在Android上请求存储权限以访问本地图片),并且确保提供的图片URL是有效的。
此外,ShareResult
对象包含了分享操作的结果信息,你可以根据需要进行处理。
希望这个示例能帮助你在Flutter项目中成功集成lecle_social_share
插件进行社交分享!