How do I open a web browser (URL) from my Flutter code?

前端 未结 7 1744
时光说笑
时光说笑 2020-12-14 05:12

I am building a Flutter app, and I\'d like to open a URL into a web browser or browser window (in response to a button tap). How can I do this?

7条回答
  •  忘掉有多难
    2020-12-14 06:02

    TL;DR

    This is now implemented as Plugin

    const url = "https://flutter.io";
    if (await canLaunch(url))
      await launch(url);
    else 
      // can't launch url, there is some error
      throw "Could not launch $url";
    

    Full example:

    import 'package:flutter/material.dart';
    import 'package:url_launcher/url_launcher.dart';
    
    void main() {
      runApp(new Scaffold(
        body: new Center(
          child: new RaisedButton(
            onPressed: _launchURL,
            child: new Text('Show Flutter homepage'),
          ),
        ),
      ));
    }
    
    _launchURL() async {
      const url = 'https://flutter.io';
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw 'Could not launch $url';
      }
    }
    

    In pubspec.yaml

    dependencies:
      url_launcher: ^5.7.10
    

    Special Characters:

    If the url value contains spaces or other values that are now allowed in URLs, use

    Uri.encodeFull(urlString) or Uri.encodeComponent(urlString) and pass the resulting value instead.

提交回复
热议问题