wechat_share_util.dart 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import 'package:flutter/cupertino.dart';
  2. import 'package:flutter/foundation.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:location/data/consts/app_config.dart';
  5. import 'package:location/sdk/wechat/wechat_helper.dart';
  6. import 'package:wechat_kit/wechat_kit.dart';
  7. import '../../data/consts/web_url.dart';
  8. import '../../resource/assets.gen.dart';
  9. import '../../resource/string.gen.dart';
  10. import '../../utils/capture_util.dart';
  11. import 'package:image/image.dart' as img;
  12. class WechatShareUtil {
  13. WechatShareUtil._();
  14. static Future<void> shareWebPage() async {
  15. if (!await WechatHelper.isInstalled()) {
  16. throw Exception(StringName.wechatNoInstall);
  17. }
  18. return WechatHelper.shareUrlToWechat(
  19. scene: WechatScene.kSession,
  20. webpageUrl: WebUrl.shareUrl,
  21. title: StringName.shareFriendTitle,
  22. description: StringName.shareFriendDesc,
  23. thumbData: await assetImageToBytes(BuildConfig.logoMaxImage.path));
  24. }
  25. static Future<Uint8List> assetImageToBytes(String assetPath) async {
  26. final ByteData byteData = await rootBundle.load(assetPath);
  27. return byteData.buffer.asUint8List();
  28. }
  29. static Future<void> shareWidgetToWeChat(
  30. GlobalKey repaintKey, {
  31. int scene = WechatScene.kSession,
  32. double pixelRatio = 2.5,
  33. int maxBytes = 1024 * 1024,
  34. }) async {
  35. try {
  36. final isInstall = await WechatHelper.isInstalled();
  37. if (!isInstall) {
  38. throw Exception(StringName.wechatNoInstall);
  39. }
  40. final captured = await CaptureUtil.captureWidgetToImage(repaintKey);
  41. if (captured == null) {
  42. throw Exception('截图失败');
  43. }
  44. final compressed =
  45. await _compressImageToLimit(captured, maxBytes: maxBytes);
  46. if (compressed == null) {
  47. debugPrint("图片压缩失败");
  48. return;
  49. }
  50. await WechatHelper.shareImageToWechat(
  51. scene: scene,
  52. imageData: compressed,
  53. );
  54. } catch (e) {
  55. throw Exception('分享失败');
  56. }
  57. }
  58. static Future<Uint8List?> _compressImageToLimit(Uint8List data,
  59. {required int maxBytes}) async {
  60. final decoded = img.decodeImage(data);
  61. if (decoded == null) return null;
  62. int quality = 95;
  63. late Uint8List result;
  64. do {
  65. result = Uint8List.fromList(img.encodeJpg(decoded, quality: quality));
  66. quality -= 5;
  67. } while (result.lengthInBytes > maxBytes && quality > 10);
  68. return result.lengthInBytes <= maxBytes ? result : null;
  69. }
  70. }