How to launch URL from flutter app

Sometimes, we may need to redirect the users of our app to a web page. we need to launch a URL from our mobile app to the browser on the device. That’s pretty easy with flutter.

First, get the url_launcher package from https://pub.dev

in your pubspec.yaml, add this line of code to dependencies section:

url_launcher: ^4.1.0

Create a new dart file with any name, i’m going to call mine launch_url.dart. add this code inside.

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

class LaunchUrlFromApp extends StatelessWidget {
  final String url = 'https://inducesmile.com';

  _launchUrl() async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not lauch URL';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Launch URL from App Example')),
      body: Center(
          child: RaisedButton(
        onPressed: _launchUrl,
        child: Text('Goto Inducesmile.com'),
        color: Colors.red,
      )),
    );
  }
}

In your main.dart file, add:

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Code Snippets',
      theme: new ThemeData(primarySwatch: Colors.red),
      home: new LaunchUrlFromApp(),
    );
  }
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment