Reputation: 1390
I'm making a WebView flutter app and I've just added app links. But when I receive app links going to my websites homepages (e.g. 1st.money/home
), I don't want those to open inside of the app, so I try and launch them back into the browser.
Here's my code so far:
import 'package:url_launcher/url_launcher.dart';
....
Future<void> openUrlInBrowser(String urlStr) async {
final Uri url = Uri.parse(urlStr);
if (!await launchUrl(
url,
mode: LaunchMode.externalApplication,
)) {
throw Exception('Could not launch $url');
}
}
This opens the URL in the browser, but then the browser immediately sends it back to the app because it's registered as an app link. This creates a loop where the URL bounces between the app and the browser.
I've also tried:
But nothing has worked yet. Has anyone else also had the problem with this? Any help would be appreciated. Thank you :)
Upvotes: 0
Views: 160
Reputation: 1
Step 1: Add url_launcher Dependency
Add the url_launcher package to your pubspec.yaml:
dependencies:
flutter:
sdk: flutter
url_launcher: ^6.1.9
Step 2: Import and Use url_launcher In your Dart code, import the url_launcher package and use the launchUrl function to open the URL in an external browser.
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Open URL in Browser')),
body: Center(
child: ElevatedButton(
onPressed: () => _launchURL('https://www.example.com'),
child: Text('Open URL'),
),
),
),
);
}
Future<void> _launchURL(String url) async {
final Uri uri = Uri.parse(url);
if (await canLaunchUrl(uri)) {
await launchUrl(
uri,
mode: LaunchMode.externalApplication,
);
} else {
throw 'Could not launch $url';
}
}
}
Create a method to launch the URL: The _launchURL method checks if the URL can be launched, and if so, it uses launchUrl with LaunchMode.externalApplication to open the URL in the external browser. Using the method: When the button is pressed, the _launchURL method is called with the desired URL.
Upvotes: 0