Flutter社交媒体分享插件md_insta_fb_share_plus的使用
Flutter社交媒体分享插件md_insta_fb_share_plus的使用
概述
md_insta_fb_share_plus
是一个 Flutter 插件,允许用户将图片分享到 Instagram 或 Facebook。此插件适用于 Android 和 iOS 平台。
使用步骤
1. 添加依赖
在 pubspec.yaml
文件中添加 md_insta_fb_share_plus
依赖:
dependencies:
flutter:
sdk: flutter
md_insta_fb_share_plus:
2. 初始化插件
确保在应用启动时初始化插件:
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
3. 示例代码
以下是一个完整的示例代码,展示了如何使用 md_insta_fb_share_plus
插件进行分享。
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:md_insta_fb_share_plus/md_insta_fb_share_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/services.dart' show rootBundle;
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ScaffoldMessenger(
key: scaffoldMessengerKey,
child: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () async {
final dir = (await getTemporaryDirectory()).path;
final data = await rootBundle.load('assets/insta_big.png');
final buffer = data.buffer;
final fileName =
'insta_big-${DateTime.now().millisecondsSinceEpoch}.png';
final file = await File('$dir/$fileName').writeAsBytes(
buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
print(await MdInstaFbShare.shareInstaStory(file.path,
"https://gruppetto.bike", "#F0C121", "#C95DC5"));
},
child: const Text('Test insta story share'),
),
ElevatedButton(
onPressed: () async {
final dir = (await getTemporaryDirectory()).path;
final data = await rootBundle.load('assets/insta_big.png');
final buffer = data.buffer;
final fileName =
'insta_big-${DateTime.now().millisecondsSinceEpoch}.png';
final file = await File('$dir/$fileName').writeAsBytes(
buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
print(await MdInstaFbShare.shareInstaFeed(file.path));
},
child: const Text('Test insta feed share'),
),
ElevatedButton(
onPressed: () async {
final dir = (await getTemporaryDirectory()).path;
final data = await rootBundle.load('assets/insta_big.png');
final buffer = data.buffer;
final fileName =
'insta_big-${DateTime.now().millisecondsSinceEpoch}.png';
final file = await File('$dir/$fileName').writeAsBytes(
buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
print(await MdInstaFbShare.shareFBStory(file.path));
},
child: const Text('Test FB story share'),
),
ElevatedButton(
onPressed: () async {
final dir = (await getTemporaryDirectory()).path;
final data = await rootBundle.load('assets/insta_big.png');
final buffer = data.buffer;
final fileName =
'insta_big-${DateTime.now().millisecondsSinceEpoch}.png';
final file = await File('$dir/$fileName').writeAsBytes(
buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
if (await InternetConnectionChecker().hasConnection) {
print(await MdInstaFbShare.shareFBFeed(file.path));
} else {
scaffoldMessengerKey.currentState?.showSnackBar(
const SnackBar(
content: Text('Internet connection error')));
}
},
child: const Text('Test FB feed share'),
),
Image.asset('assets/insta_big.png', width: 150, fit: BoxFit.fitWidth),
Row(
children: [
const Text('FB App available: '),
FutureBuilder(
future: MdInstaFbShare.checkFBInstalled(),
builder: (_, snapshot) {
if (snapshot.hasData) {
return Text('${snapshot.data}');
}
return Container();
},
)
],
),
Row(
children: [
const Text('Insta App available: '),
FutureBuilder(
future: MdInstaFbShare.checkInstaInstalled(),
builder: (_, snapshot) {
if (snapshot.hasData) {
return Text('${snapshot.data}');
}
return Container();
},
)
],
)
],
),
),
),
),
);
}
}
分享方法返回值
分享方法返回 ShareStatus
类型的值,具体如下:
enum ShareStatus {
success, // 资源成功发送到分享应用(分享应用可能没有权限,可能会抛出错误)
appCanNotBeOpenedError, // 无法打开分享应用(应用将在商店中打开)
imageNotFoundError, // 无法找到资源
galleryAccessError, // 无法保存图像到图库(需要用于 Instagram 动态分享)
unknownError // 未知错误
}
iOS 配置
在 Info.plist
文件中添加以下配置:
<key>FacebookAppID</key>
<string>{Your-FB-APP-ID}</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb{Your-FB-APP-ID}</string>
</array>
</dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>instagram-stories</string>
<string>facebook-stories</string>
<string>facebook</string>
<string>instagram</string>
<string>fbauth2</string>
<string>fbapi</string>
<string>fbapi20130214</string>
<string>fbapi20130410</string>
<string>fbapi20130702</string>
<string>fbapi20131010</string>
<string>fbapi20131219</string>
<string>fbapi20140410</string>
<string>fbapi20140116</string>
<string>fbapi20150313</string>
<string>fbapi20150629</string>
<string>fbapi20160328</string>
<string>fbauth</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
<key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to photo library</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Allow access to photo library</string>
在 AppDelegate.swift
中添加以下代码:
import UIKit
import Flutter
import FBSDKCoreKit
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
ApplicationDelegate.shared.initializeSDK();
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Android 配置
在 AndroidManifest.xml
文件中添加以下配置:
<provider android:authorities="com.facebook.app.FacebookContentProvider{Your-FB-APP-ID}"
android:name="com.facebook.FacebookContentProvider"
android:exported="true"/>
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
在 strings.xml
文件中添加以下配置:
<string name="facebook_app_id">{Your FB app ID}</string>
在 build.gradle
文件中添加以下依赖:
dependencies {
implementation 'com.facebook.android:facebook-share:latest.release'
}
更多关于Flutter社交媒体分享插件md_insta_fb_share_plus的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter社交媒体分享插件md_insta_fb_share_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
md_insta_fb_share_plus
是一个 Flutter 插件,用于在 Instagram 和 Facebook 上分享内容。它允许开发者通过简单的 API 调用来分享图片和视频到这些社交媒体平台。
安装插件
首先,你需要在 pubspec.yaml
文件中添加 md_insta_fb_share_plus
插件的依赖:
dependencies:
flutter:
sdk: flutter
md_insta_fb_share_plus: ^1.0.0 # 请检查最新版本
然后运行 flutter pub get
来安装插件。
使用插件
1. 导入插件
在你的 Dart 文件中导入插件:
import 'package:md_insta_fb_share_plus/md_insta_fb_share_plus.dart';
2. 分享图片到 Instagram
你可以使用 MdInstaFbSharePlus.shareToInstagram
方法来分享图片到 Instagram:
void shareImageToInstagram() async {
String imagePath = 'path_to_your_image.jpg'; // 本地图片路径
try {
await MdInstaFbSharePlus.shareToInstagram(imagePath: imagePath);
print('Image shared to Instagram successfully');
} catch (e) {
print('Failed to share image to Instagram: $e');
}
}
3. 分享视频到 Instagram
你可以使用 MdInstaFbSharePlus.shareVideoToInstagram
方法来分享视频到 Instagram:
void shareVideoToInstagram() async {
String videoPath = 'path_to_your_video.mp4'; // 本地视频路径
try {
await MdInstaFbSharePlus.shareVideoToInstagram(videoPath: videoPath);
print('Video shared to Instagram successfully');
} catch (e) {
print('Failed to share video to Instagram: $e');
}
}
4. 分享图片到 Facebook
你可以使用 MdInstaFbSharePlus.shareToFacebook
方法来分享图片到 Facebook:
void shareImageToFacebook() async {
String imagePath = 'path_to_your_image.jpg'; // 本地图片路径
try {
await MdInstaFbSharePlus.shareToFacebook(imagePath: imagePath);
print('Image shared to Facebook successfully');
} catch (e) {
print('Failed to share image to Facebook: $e');
}
}
5. 分享视频到 Facebook
你可以使用 MdInstaFbSharePlus.shareVideoToFacebook
方法来分享视频到 Facebook:
void shareVideoToFacebook() async {
String videoPath = 'path_to_your_video.mp4'; // 本地视频路径
try {
await MdInstaFbSharePlus.shareVideoToFacebook(videoPath: videoPath);
print('Video shared to Facebook successfully');
} catch (e) {
print('Failed to share video to Facebook: $e');
}
}
注意事项
-
路径问题: 确保你提供的图片或视频路径是设备上的有效路径。通常,你可以使用
path_provider
插件来获取设备的文件路径。 -
权限: 在 Android 上,你可能需要在
AndroidManifest.xml
中添加以下权限:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
在 iOS 上,确保在
Info.plist
中添加以下键值对:<key>NSPhotoLibraryUsageDescription</key> <string>We need access to your photo library to share images/videos</string>