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:
-
Add the
url_launcher
dependency to yourpubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
url_launcher: ^6.0.13
Don't forget to run flutter pub get
in your terminal to get the package.
- Import the required packages in your Dart file:
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
- 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';
}
}
-
Use
InkWell
orGestureDetector
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,
),
),
),
);
}
}
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,
),
),
),
);
}
}
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)