Flutter實現仿微信分享功能的示例代碼

Flutter 用來快速開發 Android iOS平臺應用,在Flutter 中,通過 fluwx或者fluwx_no_pay 插件來實現微信分享功能

主要還是看自己的需求,本示例我將按照沒有支付的實現。至於為什麼,主要是ios打包提審比較麻煩。

那麼接下來就看一下如何實現吧,

1.首先去pub官網

https://pub.flutter-io.cn/

查找這兩個包

fluwx_no_pay

或者

fluwx

安裝方式有兩種:

方法一:

flutter pub add fluwx_no_pay

方法二:

dependencies:
  fluwx_no_pay: ^3.6.1+5

然後在使用的時候導入

import 'package:fluwx_no_pay/fluwx_no_pay.dart';

雖然它集成的功能很多

但是我們隻做分享的演示

2 在微信開放平臺註冊開發者賬號以及創建你的應用程序

微信開放平臺鏈接

開發平臺文檔

創建應用填寫基本的應用信息後,提交微信平臺審核,審核通過後

從這裡拿到 AppID ,然後再將配置的 iOS 平臺的 Universal Links 拿過來,至於如何獲取,請查看相關資料。

3 在分享頁面

3.1 初始化

  @override
  void initState() {
    super.initState();
    _initFluwx();
  }

  Future _initFluwx() async {

    await WxSdk.init();

  }

3.2 檢測微信是否安裝

如點擊按鈕時進行分享,分享前檢查一下

  bool _wxIsInstalled = false;  
  void _checkWx() async {
    _wxIsInstalled = await WxSdk.wxIsInstalled();
    refreshUI();
  }

3.3 分享微信消息

 String imagePath;

imagePath = await LocalImageCache.instance
          .download(context, widget.cjinfo.cover, ext: ".jpg");
//壓縮圖片,我這兒用的flutter_image_compress

                          Uint8List image =
                              await FlutterImageCompress.compressWithFile(
                            imagePath,
                            minHeight: 128,
                            minWidth: 128,
                            quality: 20,
                            // rotate: 135,
                          );

                         WxSdk.ShareUrl(
                                  //分享鏈接
                                  "你的鏈接",
                                  scene: 1,
                                  thumbFile: imagePath,
                                  desc: "描述",
                                  title: "標題",
                                );

封裝的工具類

import 'dart:io';
import 'dart:typed_data';
import 'check.dart';
import 'package:fluwx_no_pay/fluwx_no_pay.dart' as fluwx;


class WxSdk {
  // static bool wxIsInstalled;
  static Future init() async {
    fluwx.registerWxApi(
        appId: "你的appid",
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: "你的universalLink");
  
  }

  static Future<bool> wxIsInstalled() async {
    return await fluwx.isWeChatInstalled;
  }



  /**
   * 分享圖片到微信,
   * file=本地路徑
   * url=網絡地址
   * asset=內置在app的資源圖片
   * scene=分享場景,1好友會話,2朋友圈,3收藏
   */
  static void ShareImage(
      {String title,
      String decs,
      String file,
      String url,
      String asset,
      int scene = 1}) async {
    fluwx.WeChatScene wxScene = fluwx.WeChatScene.SESSION;
    if (scene == 2) {
      wxScene = fluwx.WeChatScene.TIMELINE;
    } else if (scene == 3) {
      wxScene = fluwx.WeChatScene.FAVORITE;
    }
    fluwx.WeChatShareImageModel model = null;

    if (file != null) {
      model = fluwx.WeChatShareImageModel(fluwx.WeChatImage.file(File(file)),
          title: title, description: decs, scene: wxScene);
    } else if (url != null) {
      model = fluwx.WeChatShareImageModel(fluwx.WeChatImage.network(url),
          title: title, description: decs, scene: wxScene);
    } else if (asset != null) {
      model = fluwx.WeChatShareImageModel(fluwx.WeChatImage.asset(asset),
          title: title, description: decs, scene: wxScene);
    } else {
      throw Exception("缺少圖片資源信息");
    }
    fluwx.shareToWeChat(model);
  }

  /**
   * 分享文本
   * content=分享內容
   * scene=分享場景,1好友會話,2朋友圈,3收藏
   */
  static void ShareText(String content, {String title, int scene = 1}) {
    fluwx.WeChatScene wxScene = fluwx.WeChatScene.SESSION;
    if (scene == 2) {
      wxScene = fluwx.WeChatScene.TIMELINE;
    } else if (scene == 3) {
      wxScene = fluwx.WeChatScene.FAVORITE;
    }
    fluwx.WeChatShareTextModel model =
        fluwx.WeChatShareTextModel(content, title: title, scene: wxScene);
    fluwx.shareToWeChat(model);
  }

/***
 * 分享視頻
 * videoUrl=視頻網上地址
 * thumbFile=縮略圖本地路徑
   * scene=分享場景,1好友會話,2朋友圈,3收藏
 */
  static void ShareVideo(String videoUrl,
      {String thumbFile, String title, String desc, int scene = 1}) {
    fluwx.WeChatScene wxScene = fluwx.WeChatScene.SESSION;
    if (scene == 2) {
      wxScene = fluwx.WeChatScene.TIMELINE;
    } else if (scene == 3) {
      wxScene = fluwx.WeChatScene.FAVORITE;
    }
    fluwx.WeChatImage image = null;
    if (thumbFile != null) {
      image = fluwx.WeChatImage.file(File(thumbFile));
    }
    var model = fluwx.WeChatShareVideoModel(
        videoUrl: videoUrl,
        thumbnail: image,
        title: title,
        description: desc,
        scene: wxScene);
    fluwx.shareToWeChat(model);
  }

  /**
   * 分享鏈接
   * url=鏈接
   * thumbFile=縮略圖本地路徑
   * scene=分享場景,1好友會話,2朋友圈,3收藏
   */
  static void ShareUrl(String url,
      {String thumbFile,
      Uint8List thumbBytes,
      String title,
      String desc,
      int scene = 1,
      String networkThumb,
      String assetThumb}) {
    desc = desc ?? "";
    title = title ?? "";
    if (desc.length > 54) {
      desc = desc.substring(0, 54) + "...";
    }
    if (title.length > 20) {
      title = title.substring(0, 20) + "...";
    }
    fluwx.WeChatScene wxScene = fluwx.WeChatScene.SESSION;
    if (scene == 2) {
      wxScene = fluwx.WeChatScene.TIMELINE;
    } else if (scene == 3) {
      wxScene = fluwx.WeChatScene.FAVORITE;
    }
    fluwx.WeChatImage image = null;
    if (thumbFile != null) {
      image = fluwx.WeChatImage.file(File(thumbFile));
    } else if (thumbBytes != null) {
      image = fluwx.WeChatImage.binary(thumbBytes);
    } else if (strNoEmpty(networkThumb)) {
      image = fluwx.WeChatImage.network(Uri.encodeFull(networkThumb));
    } else if (strNoEmpty(assetThumb)) {
      image = fluwx.WeChatImage.asset(assetThumb, suffix: ".png");
    }
    var model = fluwx.WeChatShareWebPageModel(
      url,
      thumbnail: image,
      title: title,
      description: desc,
      scene: wxScene,
    );
    fluwx.shareToWeChat(model);
  }
}

check.dart

/// 字符串不為空
bool strNoEmpty(String value) {
  if (value == null) return false;

  return value.trim().isNotEmpty;
}

/// 字符串不為空
bool mapNoEmpty(Map value) {
  if (value == null) return false;
  return value.isNotEmpty;
}

///判斷List是否為空
bool listNoEmpty(List list) {
  if (list == null) return false;

  if (list.length == 0) return false;

  return true;
}

//下載圖片

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:path_provider/path_provider.dart';

class LocalImageCache {
  static LocalImageCache instance = LocalImageCache();
  String _tmepPath = "";
  void init() async {
    var tempDir = await getTemporaryDirectory();
    _tmepPath = tempDir.path;
  }


/**
 * 直接下載圖片到本地臨時目錄
 * ios必須帶有後綴,不然exists會永遠=false
 */
 

  Future<String> download(BuildContext context, String url,{String ext = ""}) async {
    try {
      var dio = await Dio()
          .get(url, options: Options(responseType: ResponseType.bytes));
      Uint8List image = Uint8List.fromList(dio.data);
      
      return save(image, url,ext: ext);
    } catch (ex) {
      print("image download error:${ex.toString()}");
      return null;
    }
  }

  
}

總結

本文設計到的知識點有

  • 如何進行微信分享
  • 如何利用dio將圖片下載到本地
  • 如何利用flutter_image_compress壓縮圖片

主要問題

未安裝微信

ios未配置白名單

圖片太大瞭(所以我用瞭壓縮技術)32k

開發平臺文檔

以上就是一些在接入微信分享過程中遇到的一些問題。

到此這篇關於Flutter實現仿微信分享功能的示例代碼的文章就介紹到這瞭,更多相關Flutter仿微信分享功能內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: