How to Open URL in External Browser in Flutter App

In this example, we are going to show you the way to open a web URL in an external browser in the Flutter app. You may need to launch URLs very often like app rating links, youtube links, or your own website. In this example, we have used Flutter package which helps to lunch URL easily. 

To add URL launcher functionality in your Flutter app, first, add the url_launcher package as a dependency in your project by adding the following lines in pubspec.yaml file. 

dependencies:
  flutter:
    sdk: flutter
  url_launcher: ^6.0.3

String url = "https://www.fluttercampus.com";
var urllaunchable = await canLaunch(url); //canLaunch is from url_launcher package
if(urllaunchable){
    await launch(url); //launch is from url_launcher package to launch URL
}else{
    print("URL can't be launched.");
}

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

void main() {
  runApp(MyApp()); 
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Test App",
        home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget{

  @override
  Widget build(BuildContext context) {
    return Scaffold( 
      appBar: AppBar( 
         title: Text("Open URL in Browser"),
         backgroundColor: Colors.redAccent,
      ),
      body: Container( 
         padding: EdgeInsets.all(20),
         child: Container( 
            height:200, 
            width:double.infinity,
            color: Colors.redAccent[50],
            child: Center( 
               child: ElevatedButton( 
                  child: Text("Open FlutterCampus.com"),
                  onPressed: () async {
                    String url = "https://www.fluttercampus.com";
                    var urllaunchable = await canLaunch(url); //canLaunch is from url_launcher package
                    if(urllaunchable){
                        await launch(url); //launch is from url_launcher package to launch URL
                    }else{
                       print("URL can't be launched.");
                    }
                  },
               )
            ),
         )
      )
    );
  }
}

Panel with URL launcher button Select Browser option when button pressed

In this way, you can make a URL launcher in an external browser in the Flutter app easily. 

No any Comments on this Article


Please Wait...