Flutter使用url_launcher调用WhatsApp发送消息时页面找不到问题
问题解决步骤
1. 修正参数传递顺序
你调用sendCodeByWhatsApp时,把消息和手机号的参数顺序搞反了。函数定义的第一个参数是手机号,第二个是消息,但你的调用代码把加密后的消息放在了第一个位置,导致URL里的phone字段变成了消息内容,自然找不到对应联系人。
修复后的调用代码:
ElevatedButton( child: const Icon(Icons.whatsapp, color: Colors.white,), onPressed: (){ // 调换参数顺序:手机号在前,消息在后 Cipher().sendCodeByWhatsApp(phone.text, encrypt.encrypt); }, ),
2. 修复URL格式错误
iOS平台的URL拼接存在语法错误:参数之间需要用&分隔,你写成了phone=$phone=$message,正确格式应该是phone=$phone&text=$message。同时,消息和手机号需要做URL编码,避免空格、特殊字符导致的解析失败。
修复后的sendCodeByWhatsApp函数:
void sendCodeByWhatsApp(String phone, String message) async { // 对手机号和消息做URL编码,处理特殊字符 final encodedPhone = Uri.encodeComponent(phone); final encodedMessage = Uri.encodeComponent(message); String url() { if (Platform.isAndroid) { return "https://wa.me/$encodedPhone/?text=$encodedMessage"; } else { // iOS平台修复参数分隔符,用&text代替=message return "https://api.whatsapp.com/send?phone=$encodedPhone&text=$encodedMessage"; } } final uri = Uri.parse(url()); if (await canLaunchUrl(uri)) { await launchUrl(uri); } else { throw 'Could not launch $uri'; } }
3. 额外注意事项
- 手机号必须包含国际区号,比如中国手机号要写成
+8613xxxxxxxxx,不能只写本地号码,否则WhatsApp无法识别对应的账号。 - 确保用户设备上已安装WhatsApp客户端,若未安装,网页版可能因格式问题无法正常跳转。
- 确认
encrypt.encrypt确实是你要发送的消息内容,检查其格式是否符合预期。
内容的提问来源于stack exchange,提问作者Osama Mohammed
相关产品推荐
相关产品推荐

