Flutter内容分享插件flutter_share_me的使用

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

Flutter内容分享插件flutter_share_me的使用

flutter_share_me

pub package style: lint

flutter_share_me 是一个Flutter插件,用于将内容分享到社交媒体。你可以使用它分享到Facebook、Instagram、WhatsApp(包括WhatsApp Business)、Twitter、Telegram以及系统分享界面。支持URL和文本。

注意:此插件仍在开发中,某些API可能尚未可用。欢迎反馈和Pull Requests!

Getting Started

添加依赖

在你的pubspec.yaml文件中添加flutter_share_me作为依赖项。请检查最新版本后再安装。

dependencies:
  flutter:
    sdk: flutter
  # add flutter_share_me
  flutter_share_me: ^0.11.0

Setup

Android配置

  1. AndroidManifest.xml文件的应用标签中添加Facebook应用ID:
    <application>
        ...
        <!--add this -->
         <meta-data
             android:name="com.facebook.sdk.ApplicationId"
             android:value="@string/facebook_app_id" />
             
         <provider
             android:name="com.facebook.FacebookContentProvider"
             android:authorities="com.facebook.app.FacebookContentProvider[facebook_app_id]"
             android:exported="false" />
     </application>
    
  2. string.xml中添加Facebook应用ID:
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <!-- Replace "343254889799245" with your Facebook App ID here. -->
        <string name="facebook_app_id">343254889799245</string>
    </resources>
    

iOS配置

确保在你的Info.plist文件中添加以下细节:

Facebook配置

<key>FacebookAppID</key>
<string>fbid</string>
<key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fb-your-fb-id</string>
            </array>
        </dict>
    </array>
<key>LSApplicationQueriesSchemes</key>
<array>
    <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>fb-messenger-share-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
    <string>tg</string>
</array>

WhatsApp配置

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>whatsapp</string>
</array>

Twitter配置

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>twitter</string>
</array>

Usage

导入包

在Dart代码中添加以下导入语句:

import 'package:flutter_share_me/flutter_share_me.dart';

方法

平台 方法
Facebook shareToFacebook({String msg, String url})
Twitter shareToTwitter({String msg, String url})
WhatsApp shareToWhatsApp({String msg, String imagePath})
WhatsApp Business (仅限Android) shareToWhatsApp4Biz({String msg, String imagePath})
WhatsApp个人消息 shareWhatsAppPersonalMessage(String message, String phoneNumber)
Instagram shareToInstagram({String filePath, FileType fileType})
Telegram shareToTelegram({String msg})
系统分享 shareToSystem({String msg})

这些方法如果成功跳转到相应应用,则返回"success"。

参数说明

参数 描述
String msg 文本消息
String url URL链接
String imagePath 图片本地路径
String filePath 文件路径
FileType fileType 文件类型

示例代码

下面是一个完整的示例,展示了如何使用flutter_share_me插件来实现不同平台的内容分享功能。

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_share_me/flutter_share_me.dart';
import 'package:image_picker/image_picker.dart';

/// 分享平台枚举
enum Share {
  facebook,
  messenger,
  twitter,
  whatsapp,
  whatsapp_personal,
  whatsapp_business,
  share_system,
  share_instagram,
  share_telegram
}

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

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

class _MyAppState extends State<MyApp> {
  File? file;
  ImagePicker picker = ImagePicker();
  bool videoEnable = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Container(
          width: double.infinity,
          child: Column(
            children: <Widget>[
              const SizedBox(height: 30),
              ElevatedButton(onPressed: pickImage, child: Text('Pick Image')),
              ElevatedButton(onPressed: pickVideo, child: Text('Pick Video')),
              ElevatedButton(
                  onPressed: () => onButtonTap(Share.twitter),
                  child: const Text('share to twitter')),
              ElevatedButton(
                onPressed: () => onButtonTap(Share.whatsapp),
                child: const Text('share to WhatsApp'),
              ),
              ElevatedButton(
                onPressed: () => onButtonTap(Share.whatsapp_business),
                child: const Text('share to WhatsApp Business'),
              ),
              ElevatedButton(
                onPressed: () => onButtonTap(Share.whatsapp_personal),
                child: const Text('share to WhatsApp Personal'),
              ),
              ElevatedButton(
                onPressed: () => onButtonTap(Share.facebook),
                child: const Text('share to FaceBook'),
              ),
              ElevatedButton(
                onPressed: () => onButtonTap(Share.messenger),
                child: const Text('share to Messenger'),
              ),
              ElevatedButton(
                onPressed: () => onButtonTap(Share.share_instagram),
                child: const Text('share to Instagram'),
              ),
              ElevatedButton(
                onPressed: () => onButtonTap(Share.share_telegram),
                child: const Text('share to Telegram'),
              ),
              ElevatedButton(
                onPressed: () => onButtonTap(Share.share_system),
                child: const Text('share to System'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> pickImage() async {
    final XFile? xFile = await picker.pickImage(source: ImageSource.gallery);
    print(xFile);
    if (xFile != null) {
      file = File(xFile.path);
      setState(() {
        videoEnable = false;
      });
    }
  }

  Future<void> pickVideo() async {
    final XFile? xFile = await picker.pickVideo(source: ImageSource.gallery);
    print(xFile);
    if (xFile != null) {
      file = File(xFile.path);
      setState(() {
        videoEnable = true;
      });
    }
  }

  Future<void> onButtonTap(Share share) async {
    String msg =
        'Flutter share is great!!\n Check out full example at https://pub.dev/packages/flutter_share_me';
    String url = 'https://pub.dev/packages/flutter_share_me';

    String? response;
    final FlutterShareMe flutterShareMe = FlutterShareMe();
    switch (share) {
      case Share.facebook:
        response = await flutterShareMe.shareToFacebook(url: url, msg: msg);
        break;
      case Share.messenger:
        response = await flutterShareMe.shareToMessenger(url: url, msg: msg);
        break;
      case Share.twitter:
        response = await flutterShareMe.shareToTwitter(url: url, msg: msg);
        break;
      case Share.whatsapp:
        if (file != null) {
          response = await flutterShareMe.shareToWhatsApp(
              imagePath: file!.path,
              fileType: videoEnable ? FileType.video : FileType.image);
        } else {
          response = await flutterShareMe.shareToWhatsApp(msg: msg);
        }
        break;
      case Share.whatsapp_business:
        response = await flutterShareMe.shareToWhatsApp(msg: msg);
        break;
      case Share.share_system:
        response = await flutterShareMe.shareToSystem(msg: msg);
        break;
      case Share.whatsapp_personal:
        response = await flutterShareMe.shareWhatsAppPersonalMessage(
            message: msg, phoneNumber: 'phone-number-with-country-code');
        break;
      case Share.share_instagram:
        response = await flutterShareMe.shareToInstagram(
            filePath: file!.path,
            fileType: videoEnable ? FileType.video : FileType.image);
        break;
      case Share.share_telegram:
        response = await flutterShareMe.shareToTelegram(msg: msg);
        break;
    }
    debugPrint(response);
  }
}

更多完整示例可以参考官方GitHub仓库

希望以上内容能帮助你更好地理解和使用flutter_share_me插件!如果你有任何问题或需要进一步的帮助,请随时提问。


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

1 回复

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


当然,以下是如何在Flutter项目中使用flutter_share_me插件的一个基本示例。flutter_share_me是一个用于在Flutter应用中实现内容分享的插件,支持多种分享渠道,如社交媒体、邮件等。

首先,确保你的Flutter开发环境已经正确配置,并且你已经创建了一个Flutter项目。

1. 添加依赖

在你的pubspec.yaml文件中添加flutter_share_me依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_share_me: ^x.y.z  # 请替换为最新版本号

然后在项目根目录运行flutter pub get来安装依赖。

2. 导入插件

在你需要分享功能的Dart文件中导入插件:

import 'package:flutter_share_me/flutter_share_me.dart';

3. 配置权限(如果需要)

某些分享渠道可能需要特定的权限,比如访问网络和读写存储。你需要在AndroidManifest.xmlInfo.plist中配置这些权限。具体权限需求请参考flutter_share_me的官方文档。

4. 使用插件

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

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SharePage(),
    );
  }
}

class SharePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter 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, this is a shared text!";
    bool result = await FlutterShareMe.shareToChannel(
      text: shareText,
      channel: ShareChannel.all,  // 可以选择具体的分享渠道,如 ShareChannel.whatsApp, ShareChannel.email 等
    );
    print("Share result: $result");
  }

  void _shareImage() async {
    String imagePath = "path/to/your/image.png";  // 替换为你的图片路径
    bool result = await FlutterShareMe.shareImage(
      imagePath: imagePath,
      channel: ShareChannel.all,  // 可以选择具体的分享渠道
    );
    print("Share result: $result");
  }
}

注意事项

  1. 图片路径:在_shareImage方法中,imagePath应该是设备上的本地图片路径,或者你可以使用asset路径(需要额外的处理来加载到本地存储)。
  2. 权限处理:确保在Android和iOS上正确配置了必要的权限,以避免运行时错误。
  3. 错误处理:在实际应用中,你应该添加错误处理逻辑来处理可能的异常情况。

这个示例展示了如何使用flutter_share_me插件来分享文本和图像。根据具体需求,你可以进一步定制分享内容、渠道和回调处理。

回到顶部