Creating a Hyperlink Button in Flutter for Web Page Navigation

Amin
mabttech
Published in
2 min readNov 16, 2023

Flutter, a popular framework for building cross-platform mobile applications, provides a straightforward way to create buttons that act as hyperlinks, allowing users to navigate to external web pages.

In this tutorial, we’ll explore how to implement a clickable button in a Flutter app that redirects users to a specified URL, such as a social media page.

Prerequisites:

Before getting started, make sure to add the url_launcher package to your Flutter project. Open your pubspec.yaml file and add the following dependency:


dependencies:
flutter:
sdk: flutter
url_launcher: ^6.2.1 # Use the latest version of url_launcher

https://pub.dev/packages/url_launcher

Then, run flutter pub get in your terminal to fetch the package.

Import Necessary Package:

In your Dart file, import the url_launcher package to use its functionality. Add the following import statement at the top of your file:

import 'package:url_launcher/url_launcher.dart';

Implementing the Hyperlink Button:

Now, let’s create a button using either the InkWell or GestureDetector widget. For this example, we'll use GestureDetector:

GestureDetector(
onTap: () {
_launchURL('https://www.facebook.com'); // Replace with your desired URL
},
child: Container(
padding: EdgeInsets.all(12.0),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(8.0),
),
child: Text(
'Visit Facebook',
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
),
),
),
)

Launching the URL:

Create a function _launchURL to handle the URL launching logic. This function checks if the device can open the specified URL and then launches it in the default web browser:

void _launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

Conclusion:

By following these steps, you’ve successfully implemented a clickable button in your Flutter app that acts as a hyperlink. This solution is versatile and works seamlessly across various platforms, including web and mobile devices. Users can tap the button, and the app will redirect them to the specified web page.

This approach is not only useful for linking to social media pages but can be applied to any external web page, providing a seamless navigation experience within your Flutter app. Whether your app is running on mobile devices, web browsers, or other platforms, the url_launcher package ensures consistent and reliable URL launching functionality.

It’s important to note that this tutorial is compatible with Flutter version 3.x and can be integrated into projects targeting multiple platforms. Feel free to customize the button’s appearance and replace the URL with the one you want to link to, creating a polished and user-friendly experience for your audience.

--

--