Flutter中如何使用url_launcher向WhatsApp特定联系人发送文件
在Flutter中通过url_launcher向特定WhatsApp联系人发送文件
首先明确:WhatsApp的wa.me链接仅支持文本消息传递,无法直接通过该链接发送文件。要实现文件发送,需要针对Android和iOS平台分别使用对应的系统Intent或URL Scheme,结合url_launcher来唤起WhatsApp并传递文件。
Android 实现步骤
Android通过系统Intent唤起WhatsApp并传入文件路径:
- 确保待发送的文件处于WhatsApp可访问的路径(比如应用外部缓存目录或公共存储)
- 构造符合WhatsApp Intent规则的URI,指定目标联系人号码与文件路径
- 使用
url_launcher启动该URI
代码示例
import 'package:url_launcher/url_launcher.dart'; import 'dart:io'; Future<void> sendFileToWhatsAppAndroid(String phoneNumber, File file) async { // 构造WhatsApp Intent URI,号码需包含国家代码(如91或+91) final uri = Uri.parse( "whatsapp://send?phone=$phoneNumber&attachment=${Uri.encodeComponent(file.path)}" ); if (await canLaunchUrl(uri)) { await launchUrl(uri, mode: LaunchMode.externalApplication); } else { throw Exception("无法打开WhatsApp,请检查是否安装"); } }
注意事项
- 权限配置:在
AndroidManifest.xml中添加对应文件读取权限(根据Android版本调整):<!-- Android 12及以下 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- Android 13+ --> <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /> <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" /> <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" /> - 文件路径推荐使用应用的外部缓存目录(通过
getExternalCacheDirectory()获取),避免权限问题。
iOS 实现步骤
iOS通过WhatsApp的URL Scheme传递文件,但需要将文件复制到WhatsApp可访问的共享目录:
- 将待发送文件复制到应用文档目录(iOS中只有该目录下的文件能被其他App访问)
- 构造包含号码和文件路径的URI
- 使用
url_launcher启动URI
代码示例
import 'package:url_launcher/url_launcher.dart'; import 'package:path_provider/path_provider.dart'; import 'dart:io'; Future<void> sendFileToWhatsAppIOS(String phoneNumber, File file) async { // 将文件复制到应用文档目录,确保WhatsApp可访问 final docsDir = await getApplicationDocumentsDirectory(); final sharedFile = File("${docsDir.path}/${file.path.split('/').last}"); await file.copy(sharedFile.path); // 构造WhatsApp URL Scheme final uri = Uri.parse( "whatsapp://send?phone=$phoneNumber&attachment=${Uri.encodeComponent(sharedFile.path)}" ); if (await canLaunchUrl(uri)) { await launchUrl(uri, mode: LaunchMode.externalApplication); } else { throw Exception("无法打开WhatsApp,请检查是否安装"); } }
注意事项
- 在
Info.plist中添加WhatsApp Scheme白名单:<key>LSApplicationQueriesSchemes</key> <array> <string>whatsapp</string> </array> - iOS 14+需确保应用拥有文件访问权限,可通过
permission_handler包申请相关权限。
跨平台封装
可以封装一个统一方法,根据当前平台自动调用对应实现:
import 'dart:io'; Future<void> sendFileToWhatsApp(String phoneNumber, File file) async { if (Platform.isAndroid) { await sendFileToWhatsAppAndroid(phoneNumber, file); } else if (Platform.isIOS) { await sendFileToWhatsAppIOS(phoneNumber, file); } else { throw Exception("当前平台不支持该功能"); } }
替代方案
如果上述方式在特定版本的WhatsApp或系统中失效,可以考虑使用专门的WhatsApp分享插件(如whatsapp_share),这类插件封装了更稳定的原生调用逻辑。但如果坚持使用url_launcher,上述方案是当前最接近文本发送方式的实现。
内容的提问来源于stack exchange,提问作者Venkat Pandi
相关产品推荐
相关产品推荐

