A2oz

How Do I Add a Link to My Website in Flutter?

Published in Flutter Development 2 mins read

You can add a link to your website in Flutter by using the TextButton widget. This widget allows you to create a clickable button that, when pressed, will open the specified URL in a web browser.

Steps to Add a Link:

  1. Import the necessary package:

    import 'package:flutter/material.dart';
  2. Create a TextButton widget:

    TextButton(
      onPressed: () {
        // Open the website URL in a web browser
        launch('https://www.yourwebsite.com');
      },
      child: const Text('Visit Our Website'),
    )
  3. Replace https://www.yourwebsite.com with your actual website URL.

Example:

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart'; // Import the url_launcher package

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Link Example'),
      ),
      body: Center(
        child: TextButton(
          onPressed: () async {
            // Launch the website URL
            final Uri url = Uri.parse('https://www.example.com');
            if (await canLaunchUrl(url)) {
              await launchUrl(url);
            } else {
              throw 'Could not launch $url';
            }
          },
          child: const Text('Visit Example Website'),
        ),
      ),
    );
  }
}

Note: You need to add the url_launcher package to your project to use the launchUrl function.

Additional Tips:

  • You can customize the appearance of the TextButton widget by using properties like style, padding, and textColor.
  • You can use other widgets like ElevatedButton or OutlinedButton to create different styles of clickable buttons.
  • You can also use the launch function from the url_launcher package to open other types of URLs, such as email addresses, phone numbers, or maps.

Related Articles