DEV Community

Cover image for How do you add a link to a button in Flutter?
Nikhil Soman Sahu
Nikhil Soman Sahu

Posted on

How do you add a link to a button in Flutter?

Hyperlinks can be quite easily integrated in Flutter apps with the help of certain packages. In Flutter, we can create a button with a link by using the InkWell or GestureDetector widget to detect taps, and then navigate to the desired URL using the launch function from the url_launcher package. Here's a step-by-step guide:

  1. Add the url_launcher dependency to your pubspec.yaml file:
   dependencies:
     flutter:
       sdk: flutter
     url_launcher: ^6.0.13
Enter fullscreen mode Exit fullscreen mode

Don't forget to run flutter pub get in your terminal to get the package.

  1. Import the required packages in your Dart file:
   import 'package:flutter/material.dart';
   import 'package:url_launcher/url_launcher.dart';
Enter fullscreen mode Exit fullscreen mode
  1. Create a function to launch the URL:
   _launchURL() async {
     const url = 'https://example.com'; // Replace with your desired URL
     if (await canLaunch(url)) {
       await launch(url);
     } else {
       throw 'Could not launch $url';
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Use InkWell or GestureDetector to wrap your button:
   class MyButtonWithLink extends StatelessWidget {
     @override
     Widget build(BuildContext context) {
       return InkWell(
         onTap: () {
           _launchURL();
         },
         child: Container(
           padding: EdgeInsets.all(12.0),
           decoration: BoxDecoration(
             color: Colors.blue,
             borderRadius: BorderRadius.circular(8.0),
           ),
           child: Text(
             'Visit Website',
             style: TextStyle(
               color: Colors.white,
               fontSize: 16.0,
             ),
           ),
         ),
       );
     }
   }
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can use GestureDetector:

   class MyButtonWithLink extends StatelessWidget {
     @override
     Widget build(BuildContext context) {
       return GestureDetector(
         onTap: () {
           _launchURL();
         },
         child: Container(
           padding: EdgeInsets.all(12.0),
           decoration: BoxDecoration(
             color: Colors.blue,
             borderRadius: BorderRadius.circular(8.0),
           ),
           child: Text(
             'Visit Website',
             style: TextStyle(
               color: Colors.white,
               fontSize: 16.0,
             ),
           ),
         ),
       );
     }
   }
Enter fullscreen mode Exit fullscreen mode

Now, when the button is tapped, it will launch the specified URL in the default web browser. Adjust the URL and button styling to fit your specific requirements.

Top comments (0)