I have a little link in my app that says "Send us an e-mail". When you click it, I want the default email app to open, with an email started to our email address. I used to make it do exactly that with the launch()
method in the url_launcher
package like this:
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;
}
But now, I get a warning saying launch()
is deprecated! I should use launchUrl()
instead. But launchUrl()
doesn't take a String argument, it takes a Uri argument... and I don't know how to write this Uri correctly, so that it does what I want! I tried:
success = await url.launchUrl(Uri(path: 'mailto:[email protected]'));
but that throws an error, because it can't interpret the ":" character. I've tried:
success = await url.launchUrl(
Uri.https('mailto:[email protected]', ''),
);
and that launches the link, but in the browser... and it doesn't start up an e-mail to the pre-printed address. I tried adding:
success = await url.launchUrl(
Uri.https('mailto:[email protected]', ''),
mode: url.LaunchMode.externalApplication,
);
and that gives me an option of which external app to open the link with, but unfortunately, only browser apps are listed... not the email app!
How should I write my command to make the launchUrl()
just do exactly what the old launch()
did?? Most grateful for help!
CodePudding user response:
Try this:
void _sendEmail(){
String? encodeQueryParameters(Map<String, String> params) {
return params.entries.map((e) =>
'${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
.join('&');
}
final Uri emailLaunchUri = Uri(
scheme: 'mailto',
path: '[email protected]',
query: encodeQueryParameters(<String, String>{
'subject': 'CallOut user Profile',
'body': widget.userModel?.username ?? ''
}),
);
launchUrl(emailLaunchUri);
}
CodePudding user response:
No need for the other answer's pointless redundant subroutine when it's already built in to Uri
!
void _sendEmail(){
final Uri emailLaunchUri = Uri(
scheme: 'mailto',
path: '[email protected]',
queryParameters: {
'subject': 'CallOut user Profile',
'body': widget.userModel?.username ?? ''
}),
);
launchUrl(emailLaunchUri);
}