In Flutter web, you can navigate to a link in a new tab without relying on Android-specific code by using the url_launcher
package. Here’s how you can do it:
- Add the
url_launcher
package to yourpubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
url_launcher: ^6.0.9
Update your Dart code to use url_launcher
:dart
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 Link in New Tab Example'),
),
body: Center(
child: ElevatedButton(
onPressed: _launchURL,
child: Text('Open Flutter Website'),
),
),
),
);
}
void _launchURL() async {
const url = 'https://flutter.dev';
if (await canLaunch(url)) {
await launch(
url,
webOnlyWindowName: '_blank', // This will open the link in a new tab
);
} else {
throw 'Could not launch $url';
}
}
}
- Explanation:
- The
url_launcher
package provides a methodlaunch
which can be used to open URLs. - The
webOnlyWindowName: '_blank'
parameter ensures that the link opens in a new tab when running in a web environment. - The
canLaunch
method checks if the URL can be launched.
- The
By using the url_launcher
package and specifying webOnlyWindowName: '_blank'
, you ensure that the URL opens in a new tab on Flutter web, providing a platform-independent solution.