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

前端 未结 7 1714
时光说笑
时光说笑 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 05:46

    The best way is to use url_launcher package .

    Add url_launcher as a dependency in your pubspec.yaml file.

    dependencies:
      url_launcher: ^5.7.10
    

    An example of how to use it :

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

    Output :

    The launch method takes a string argument containing a URL . By default, Android opens up a browser when handling URLs. You can pass forceWebView: true parameter to tell the plugin to open a WebView instead. If you do this for a URL of a page containing JavaScript, make sure to pass in enableJavaScript: true, or else the launch method will not work properly. On iOS, the default behavior is to open all web URLs within the app. Everything else is redirected to the app handler.

提交回复
热议问题