How to resolve could not launch Error in Url launcher - flutter

I am trying open a link on Google pixel API 30 Emulator but keep on getting error. Have tried flutter clean, restarted app.
Dependency:-
url_launcher: ^6.0.3
Code:-
InkWell(
onTap:() => _launchURL("https://google.com"),
child: Image.asset("assets/images/googleIcon.jpg")
),
_launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Error:-
Unhandled Exception: Could not launch https://google.com

Add a URI class since url_launcher recommends encoding the URLs as URI. Link to Doc
final Uri _faireGitHubUri = Uri.https('google.com', '/');
InkWell(
onTap:() => _launchURL(_websiteUri.toString()),
child: Image.asset("assets/images/googleIcon.jpg")
),

Related

Flutter how to open pdf using web browser

How to open pdf from url address in flutter?
I try call window like this:
And select there application for open pdf file.
I try do it using libraries:
https://pub.dev/packages/pdfx
https://pub.dev/packages/url_launcher
But none of them cannot do it. Any ideas or samples?
You can force webview using
Future<void> _launchInBrowser(Uri url) async {
if (!await launchUrl(
url,
mode: LaunchMode.externalApplication,
)) {
throw 'Could not launch $url';
}
}
or to load it in an inapp web view
Future<void> _launchInWebViewOrVC(Uri url) async {
if (!await launchUrl(
url,
mode: LaunchMode.inAppWebView,
webViewConfiguration: const WebViewConfiguration(
headers: <String, String>{'my_header_key': 'my_header_value'}),
)) {
throw 'Could not launch $url';
}
}

Flutter app crashing when permission for location is denied with Huawei Location

I am implementing getting device location for Huawei devices, it is working when permission is granted but when is denied app is crashing.
With location from google it never happened.
Here is my code for getting location:
Future<Location?> getAccuratePositionH() async {
PermissionHandler permissionHandler = PermissionHandler();
bool status = await permissionHandler.requestLocationPermission();
if (status) {
FusedLocationProviderClient locationService = FusedLocationProviderClient();
Location location = await locationService.getLastLocation();
return location;
}
else {
return null;
}
}
This is what I am getting in console:
I/cgr.qrmv.QrMobVisPlugin( 5178): Permissions request denied.
W/cgr.qrmv.QrMobVisPlugin( 5178): Starting QR Mobile Vision failed
W/cgr.qrmv.QrMobVisPlugin( 5178): com.github.rmtmckenzie.qrmobilevision.QrReader$Exception: QR reader failed because noPermissions
and
java.lang.RuntimeException: Failure delivering result ResultInfo{who=#android:requestPermissions:, request=1, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.lea24.partyfinder/com.lea24.partyfinder.MainActivity}: java.lang.NullPointerException: Attempt to read from field 'io.flutter.plugin.common.MethodChannel$Result com.github.rmtmckenzie.qrmobilevision.QrMobileVisionPlugin$ReadingInstance.startResult' on a null object reference
Why is here QR Mobile Vision? I don't know, really, it's happening after denied location permissions.
What am I doing wrong and how to fix it?
If permission is denied once it is denied permanently. So, users have to change it from settings manually. All you can do is redirect the user to settings.
Before asking for permission make sure permission is not already denied otherwise it will crash your app without any warning, as given below in the code.
Below is a code using permission_handler to request permission and Getx to show the contextless dialog. This function will return the status of permission and you can proceed using it by checking if it is allowed or not as
PermissionStatus status = await requestLocalStoragePermission();
if (status.isGranted) {
//proceed
}
Full Code
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
Future<PermissionStatus> requestLocalStoragePermission() async {
PermissionStatus status;
if ((await Permission.storage.isPermanentlyDenied) ||
(await Permission.storage.isDenied)) {
status = PermissionStatus.denied;
Get.dialog(
AlertDialog(
//Getx dialog is used, you may use default other dialog based on your requirement
title: const Text(
"Storage permission required!",
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(30.0)),
content: const Text(
"Storage permission is required to download files",
textAlign: TextAlign.center,
),
actions: <Widget>[
Center(
child: TextButton(
onPressed: () async => {
await openAppSettings(), //function in permission_handler
Get.back() //close dialog
},
child: const Text("Grant Permission"),
),
),
],
),
);
} else {
try {
status = await Permission.storage.request();
} catch (err) {
status = PermissionStatus.denied;
}
}
return status;
}

How to open URL in flutter app with url_launcher?

I use the package url_launcher to open url, here is the code:
Future <void> _openURL(String url) async{
if(await canLaunch(url)) {
await launch(
url,
forceSafariVC: false,
forceWebView: true,
);
}
else{
throw 'Cant open URL';
}
}
ListTile(
title: Text('Google'),
onTap: () {
_openURL('https://www.google.de/');
}),
But no matter what url i want to open, i get the error 'Cant open URL'
I get the same error: Unhandled Exception: Could not launch
As you can see here https://pub.dev/packages/url_launcher you have to put the following snippet at your AndroidManifest.xml
<queries>
<!-- If your app opens https URLs -->
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https" />
</intent>
</queries>
Try to below code:
Create launchURL function :
_launch() async {
const url = 'https://www.google.de/';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Create your Widget :
ListTile(
onTap: _launch,
title: Text('Google'),
),
Hope its solved your problem
I was not able to open the URL in Android using Flutter app with pub file https://pub.dev/packages/url_launcher
Since JavaScript was not enable.
Here's working code snippet for Android -
void _launchURL(String _url) async {
if (await canLaunch(_url)) {
await launch(_url, forceSafariVC: true, forceWebView: true, enableJavaScript: true);
} else {
throw 'Could not launch $_url';
}
}
Then I added a key enableJavaScript: true and it started working on Android too. iOS no need for configuration.

How to open installed app with url_launcher else open in browser?

like the title suggests, I use url_launcher to open some websites when the user taps a selected icon. The issue is that it opens the browser website if the associated app is not installed on the device otherwise nothing happens if said app is installed. The app just doesn't respond. From what I've read, its supposed to open the associated app anyway? Or am I mistaken?
Here's the onTap:
GestureDetector(
onTap: _launchTwitchURL,
child: Image.asset(
'assets/images/icon_twitch.png', // On click should redirect to an URL
width: 40.0,
height: 40.0,
),
),
And here's the call:
Future<void> _launchTwitchURL() async {
const url = 'https://www.twitch.tv/example';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Using android-intent package like #iDecode suggested to get it to work. appavailability might be a better suited/cleaner package depending on your needs.
Future<void> _launchTwitchURL() async {
const url = 'https://www.twitch.tv/example';
if (await canLaunch(url)) {
await launch(url);
} else if (Platform.isAndroid) {
final AndroidIntent intent = AndroidIntent(
action: 'action_view',
data: 'https://www.twitch.tv/example', // replace com.example.app with your applicationId
);
await intent.launch();
} else {
throw 'Could not launch $url';
}
}
Thanks #iDecode

How to send sms with URL_launcher package with flutter?

Hello I search a simple example (Android and iOS) to send SMS with this package
https://pub.dartlang.org/packages/url_launcher
In the plugin page I only see how to open sms native app with phone number, but no extra message
sms:<phone number>, e.g. sms:5550101234 Send an SMS message to <phone
number> using the default messaging app
On Android the full sms: URI is supported and you can send a message with a body like that (RFC5724):
_textMe() async {
// Android
const uri = 'sms:+39 348 060 888?body=hello%20there';
if (await canLaunch(uri)) {
await launch(uri);
} else {
// iOS
const uri = 'sms:0039-222-060-888?body=hello%20there';
if (await canLaunch(uri)) {
await launch(uri);
} else {
throw 'Could not launch $uri';
}
}
}
On iOS the official doc says you can only use the number field of The URI.
Instead as Konstantine pointed out, if you use a non standard URI and instead and instead of starting the query string with ? you use & it still works as well. It seems like an undocumented feature.
The sms scheme is used to launch the Messages app. The format for URLs
of this type is “sms:”, where is an optional parameter
that specifies the target phone number of the SMS message. This
parameter can contain the digits 0 through 9 and the plus (+), hyphen
(-), and period (.) characters. The URL string must not include any
message text or other information.
PS. to check the plaform you could use the dart.io library Platform class:
_textMe() async {
if (Platform.isAndroid) {
const uri = 'sms:+39 348 060 888?body=hello%20there';
await launch(uri);
} else if (Platform.isIOS) {
// iOS
const uri = 'sms:0039-222-060-888&body=hello%20there';
await launch(uri);
}
}
you can trying this for android and IOS:
sendMessage() async {
if(Platform.isAndroid){
//FOR Android
url ='sms:+6000000000?body=message';
await launch(url);
}
else if(Platform.isIOS){
//FOR IOS
url ='sms:+6000000000&body=message';
}
}
This answer is for the new people coming in here for answers.
The previous answers are right however they won't work on iOS.
The App might crash on iOS but work on Android.
so to solve that we need to implement sending SMS in the way given below
String? encodeQueryParameters(Map<String, String> params) {
return params.entries
.map((e) => '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
.join('&');
}
Uri smsUri = Uri(
scheme: 'sms',
path: '$phoneNumber',
query: encodeQueryParameters(<String, String>{
'body':
'Hey this is message body'
}),
);
try {
if (await canLaunch(smsUri.toString())) {
await launch(smsUri.toString());
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Some error occured'),
),
);
}
Final updated answer post flutter 3 and latest url launcher package
smsUri = Uri(scheme: 'sms', path: phoneNumber);
try {
print(smsUri.toString());
if (await canLaunchUrl(
smsUri,
)) {
await launchUrl(smsUri);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: const Text('Some error occured'),
),
);
}
Here is the updated answer for sending SMS based on the OS of the device. I have tried the previous answers but I was facing body text issues on IOS devices.
_launchSms() async {
try {
if (Platform.isAndroid) {
String uri = 'sms:$phoneNumber?body=${Uri.encodeComponent("Hello there")}';
await launchUrl(Uri.parse(uri));
} else if (Platform.isIOS) {
String uri = 'sms:$phoneNumber&body=${Uri.encodeComponent("Hello there")}';
await launchUrl(Uri.parse(uri));
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Some error occurred. Please try again!'),
),
);
}
}