Flutter社交分享插件new_social_share的使用
Flutter社交分享插件new_social_share的使用
简介
new_social_share
插件提供了多种分享选项,可以将内容直接分享到某些热门应用,或者通过默认的原生分享功能进行分享。该插件适用于 Android
和 iOS
平台。
感谢
本插件基于 ShekarMudaliyar 的原始工作。感谢这位开发者的重要贡献,这为我们开发此升级版并增强其功能提供了灵感。
使用方法
Android 配置
在 android/app/src/main/AndroidManifest.xml
文件中添加以下属性:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="your.package.name">
在 <application>
标签内添加以下代码:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.com.ibrohim.new_social_share.new_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>
在 app/src/main/res/xml
文件夹中创建一个名为 filepaths.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 配置
在 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,还需要在 Info.plist
文件中添加以下代码:
<key>FacebookAppID</key>
<string>xxxxxxxxxxxxxxx</string>
示例代码
下面是一个完整的示例代码,展示了如何使用 new_social_share
插件进行各种社交分享操作。
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:new_social_share/new_social_share.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';
import 'package:screenshot/screenshot.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String facebookId = "xxxxxxxx"; // 替换为你的 Facebook 应用 ID
var imageBackground = "image-background.jpg";
var videoBackground = "video-background.mp4";
String imageBackgroundPath = "";
String videoBackgroundPath = "";
[@override](/user/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);
var path = file?.path;
if (path == 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](/user/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());
});
},
),
],
),
],
),
),
),
),
),
);
}
}
更多关于Flutter社交分享插件new_social_share的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter社交分享插件new_social_share的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用new_social_share
插件进行社交分享的示例代码。这个插件允许你通过不同的社交媒体平台分享文本、图像、URL等内容。
首先,确保你的Flutter项目已经创建,并且你已经在pubspec.yaml
文件中添加了new_social_share
插件的依赖:
dependencies:
flutter:
sdk: flutter
new_social_share: ^0.2.2 # 请检查最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,在你的Dart文件中(例如main.dart
),你可以按照以下方式使用new_social_share
插件:
import 'package:flutter/material.dart';
import 'package:new_social_share/new_social_share.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Social Share Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SocialShareDemo(),
);
}
}
class SocialShareDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Social Share Demo'),
),
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'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
_shareUrl();
},
child: Text('Share URL'),
),
],
),
),
);
}
void _shareText() {
SocialShare()
.shareText(
text: "Hello, I am sharing some text via Flutter!",
subject: "Text Share",
)
.then((result) {
print("Text share result: $result");
})
.catchError((error) {
print("Error sharing text: $error");
});
}
void _shareImage() {
SocialShare()
.shareImage(
imageUrl: "https://example.com/path/to/your/image.jpg",
)
.then((result) {
print("Image share result: $result");
})
.catchError((error) {
print("Error sharing image: $error");
});
}
void _shareUrl() {
SocialShare()
.shareUrl(
url: "https://www.example.com",
title: "Example Website",
description: "This is an example of sharing a URL.",
)
.then((result) {
print("URL share result: $result");
})
.catchError((error) {
print("Error sharing URL: $error");
});
}
}
在这个示例中,我们创建了一个简单的Flutter应用,它有三个按钮:一个用于分享文本,一个用于分享图像,还有一个用于分享URL。每个按钮点击时都会调用相应的_shareText
、_shareImage
或_shareUrl
方法。
请注意,实际使用中你可能需要处理更复杂的场景,比如处理不同的平台(iOS和Android)的特定配置,或者处理用户取消分享操作的情况。new_social_share
插件的文档会提供这些方面的更多详细信息。