In Flutter web, you can use the url_launcher
package to open URLs in a new tab. Here’s how you can navigate to a route in a new tab:
- First, add the
url_launcher
dependency to yourpubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
url_launcher: ^6.0.3
- Install the package by running
flutter pub get
in your terminal. - Then, you can use the
url_launcher
package to open URLs in a new tab. Here’s an example of how to navigate to a route in a new tab:
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(
title: 'Flutter Demo',
home: Scaffold(
appBar: AppBar(
title: Text('Navigate in new tab'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
_launchURL(context, '/newRoute');
},
child: Text('Navigate in new tab'),
),
),
),
);
}
void _launchURL(BuildContext context, String route) async {
final url = 'http://flutterfever.com$route';
if (await canLaunch(url)) {
await launch(url, forceSafariVC: false, forceWebView: false);
} else {
// Handle error
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Could not launch $url'),
));
}
}
}
Replace 'http://flutterfever.com$route'
with your actual website URL and the route you want to navigate to. This code will open the URL in a new tab. If you want to use relative routes, make sure to add your base URL accordingly.
Remember to handle URL launching errors appropriately based on your app’s requirements.
How to open link in same Tab in flutter web?
Import dart:html
in your script.
import 'dart:html' as html;
Open Link in the Same Tab:
html.window.open('https://www.flutterfever.com',"_self");
//html is from import
Open Link in New Tab:
html.window.open('https://www.flutterfever.com',"_blank");
Open Link in New Window:
html.window.open('https://www.flutterfever.com',"_blank", 'location=yes');