我的应用程序中有一个小链接,上面写着“向我们发送电子邮件”。当您单击它时,我希望打开默认电子邮件应用程序,并向我们的电子邮件地址发送一封电子邮件。我曾经用
launch()
包中的 url_launcher
方法让它做到这一点,如下所示:
import 'package:url_launcher/url_launcher.dart' as url;
Future<bool?> pressedSendUsEmail() async {
bool? success;
try {
print('Pressed Send us an e-mail...');
success = await url.launch('mailto:[email protected]'); // Works like a charm...
print('success is $success');
} catch (e) {
print('Caught an error in Send us an e-mail!');
print('e is: ${e.toString()}');
}
return success;
}
但是现在,我收到一条警告,说
launch()
已弃用!我应该用 launchUrl()
来代替。但是 launchUrl()
不接受 String 参数,它接受 Uri 参数...并且我不知道如何正确编写这个 Uri,以便它执行我想要的操作!我试过:
success = await url.launchUrl(Uri(path: 'mailto:[email protected]'));
但这会引发错误,因为它无法解释“:”字符。我试过:
success = await url.launchUrl(
Uri.https('mailto:[email protected]', ''),
);
然后启动链接,但是在浏览器中......并且它不会启动发送到预先打印的地址的电子邮件。我尝试添加:
success = await url.launchUrl(
Uri.https('mailto:[email protected]', ''),
mode: url.LaunchMode.externalApplication,
);
这让我可以选择使用哪个外部应用程序打开链接,但不幸的是,仅列出了浏览器应用程序......而不是电子邮件应用程序!
我应该如何编写命令才能使
launchUrl()
完全按照旧的 launch()
所做的那样?非常感谢您的帮助!
编辑:
在下面这个问题得到满意的回答后,我现在有一个后续问题:
在应用程序的另一部分,有一个地方可以让用户输入链接,我曾经用
launch()
来启动它...还有一个简单的方法可以做到这一点吗?
因为在这种情况下,我不知道链接是 http 还是 https 或者确实是 mailto:!...而且我宁愿不必编写大量代码来找出答案!我只是希望它尝试完全按照编写的方式启动链接,只要编写正确,它就会起作用。
试试这个:
void _sendEmail(){
final Uri emailLaunchUri = Uri(
scheme: 'mailto',
path: '[email protected]',
queryParameters: {
'subject': 'CallOut user Profile',
'body': widget.userModel?.username ?? ''
},
);
launchUrl(emailLaunchUri);
}
当其他答案已经内置到
Uri
时,不需要其他答案的无意义的冗余子例程!
void _sendEmail(){
final Uri emailLaunchUri = Uri(
scheme: 'mailto',
path: '[email protected]',
queryParameters: {
'subject': 'CallOut user Profile',
'body': widget.userModel?.username ?? ''
},
);
launchUrl(emailLaunchUri);
}
内置查询生成器仅适用于 http/https。
对于其他任何事情都应该使用以下内容。否则你将得到“+”而不是空格。
String? encodeQueryParameters(Map<String, String> params) {
return params.entries
.map((MapEntry<String, String> e) =>
'${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
.join('&');
}
///
void _sendEmail() {
final Uri emailLaunchUri = Uri(
scheme: 'mailto',
path: '[email protected]',
query: encodeQueryParameters({
'subject': 'CallOut user Profile',
'body': widget.userModel?.username ?? ''
}),
);
launchUrl(emailLaunchUri);
}