I'm new to Flutter, so here's a solution that worked in my project; it may not be the only way. I just wanted to provide my own version for new users like me.
Notes:
This uses package:web, which replaces the now-deprecated dart:html.
window.open(url, '_blank') attempts to open in a new tab, but if the browser blocks it (due to pop-up blockers or the Google App on iOS), it falls back to navigating in the current tab.
Calling openUrl(answerUrl, newTab: false) opens in the same tab.
import 'package:web/web.dart' as web;
// link to open
const answerUrl = 'https://stackoverflow.com/questions/ask';
// function to open link in new tab or same page
void openUrl(String url, {bool newTab = true}) {
try {
if (newTab) {
// opens new tab
final newWindow = web.window.open(url, '_blank');
if (newWindow == null) {
// Fallback if browser blocks the popup
web.window.location.href = url;
}
} else {
// Open directly in the same tab
web.window.location.href = url;
}
} catch (_) {
// Fallback for cases like Google App on iPhone
web.window.location.href = url;
}
}
// ... passing the link to the function inside onPressed
ElevatedButton(
onPressed: () => openUrl(answerUrl),
child: const Text("Go to questions"),
)