Technology Sharing

How to open the corresponding hyperlink after clicking a text in flutter

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

How to open the corresponding hyperlink after clicking a text in flutter

Flutter can open a URL in the browser after clicking on the text, for example "www.baidu.com". This can be done by using url_launcher package to do this. First, you need topubspec.yaml Add to the fileurl_launcher rely.

  url_launcher: ^6.3.0

Here is the sample code

  1. import 'package:flutter/material.dart';
  2. import 'package:url_launcher/url_launcher.dart';
  3. final Uri _url = Uri.parse('https://www.baidu.com');
  4. void main() => runApp(
  5. const MaterialApp(
  6. home: Material(
  7. child: Center(
  8. child: ElevatedButton(
  9. onPressed: _launchUrl,
  10. child: Text('点击打开百度'),
  11. ),
  12. ),
  13. ),
  14. ),
  15. );
  16. Future<void> _launchUrl() async {
  17. if (!await launchUrl(_url)) {
  18. throw Exception('Could not launch $_url');
  19. }
  20. }