'mailto: link for Flutter for Web
The url_launcher package (https://pub.dev/packages/url_launcher) doesn't seem to work for Flutter for Web. The following code prints "test url1" but nothing happens afterwards.
How can I implement mailto:
like functionality in Flutter for Web which causes the default email app to open with a prepopulated 'to:' email address?
FlatButton(
onPressed: _mailto, //() => {},
padding: EdgeInsets.all(3.0),
child: _contactBtn(viewportConstraints),
)
_mailto() async {
const url = 'mailto:[email protected]?subject=Product Inquiry&body=';
print("test url1");
if (await canLaunch(url)) {
print("test url2");
await launch(url);
} else {
print("test url3");
throw 'Could not launch $url';
}
}
Solution 1:[1]
After experimenting a little I found a way to make url_launcher work with web.
Don't use canLaunch(url)
. Instead, just use launch(url)
, but wrap it in try-catch block. This way you should be safe and the email link will work. For catch you can just copy the email to clipboard and notify the user about that with a snackbar or smth. Probably not the best solution, but a good one, till we get something better.
Here is the sample code, so that you see what I mean:
void _launchMailClient() async {
const mailUrl = 'mailto:$kEmail';
try {
await launch(mailUrl);
} catch (e) {
await Clipboard.setData(ClipboardData(text: '$kEmail'));
_emailCopiedToClipboard = true;
}
}
Solution 2:[2]
import 'package:mailto/mailto.dart';
// For Flutter applications, you'll most likely want to use
// the url_launcher package.
import 'package:url_launcher/url_launcher.dart';
// ...somewhere in your Flutter app...
launchMailto() async {
final mailtoLink = Mailto(
to: ['[email protected]'],
cc: ['[email protected]', '[email protected]'],
subject: 'mailto example subject',
body: 'mailto example body',
);
// Convert the Mailto instance into a string.
// Use either Dart's string interpolation
// or the toString() method.
await launch('$mailtoLink');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mono |
Solution 2 | Phortuin |