Implementing a Web Browser in Flutter using flutter_web_browser Package ?

Spread the love
flutter web browser example app
Implementing a Web Browser in Flutter using flutter_web_browser Package ?

 

flutter web browser example ap
Implementing a Web Browser in Flutter using flutter_web_browser Package ?

Introduction:

The flutter_web_browser package allows you to open web pages in a browser from your Flutter app. This guide will show you how to use this package to implement a simple web browser in your Flutter app.

Content:

1.Add the flutter_web_browser dependency:

Open your pubspec.yaml file and add the flutter_web_browser dependency.

Run flutter pub get to install the package.

 

2.Import the package:

Import the flutter_web_browser package in your Dart file.


import 'package:flutter_web_browser/flutter_web_browser.dart';

3.Open a web page in the browser:

Use the FlutterWebBrowser.openWebPage method to open a web page in the default browser.


void openBrowser() async {
  await FlutterWebBrowser.openWebPage(
    url: 'https://www.example.com',
    androidToolbarColor: Colors.deepPurple,
  );
}

Replace 'https://www.example.com' with the URL of the web page you want to open. You can also customize the browser’s toolbar color for Android using the androidToolbarColor parameter.

 

4.Create a button to open the browser:

Add a button to your UI that calls the openBrowser method when pressed.


ElevatedButton(
  onPressed: openBrowser,
  child: Text('Open Web Page'),
)

This button will open the specified web page in the browser when pressed.

 

Sample Output:


// ignore_for_file: unnecessary_new, prefer_const_constructors

import 'dart:async';
import 'dart:io';

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future<void> openBrowserTab() async {
    await FlutterWebBrowser.openWebPage(url: "https://flutterone.com/");
  }

  List<BrowserEvent> _events = [];

  StreamSubscription<BrowserEvent>? _browserEvents;

  @override
  void initState() {
    super.initState();

    _browserEvents = FlutterWebBrowser.events().listen((event) {
      setState(() {
        _events.add(event);
      });
    });
  }

  @override
  void dispose() {
    _browserEvents?.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('flutter_web_browser example app'),
        ),
        body: new Center(
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Text(
                    "The flutter_web_browser package is a Flutter plugin that allows you to open web pages in the default web browser of the device. It provides a simple API for opening URLs, making it easy to launch web content from your Flutter app.",
                    style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold),
                    textAlign: TextAlign.center),
                SizedBox(
                  height: 20,
                ),
                TextButton(
                  style: ElevatedButton.styleFrom(
                    primary: Colors.blue, // Background color
                    onPrimary: Colors.white, // Text color
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0), // Button border radius
                    ),
                  ),
                  onPressed: () => FlutterWebBrowser.warmup(),
                  child: Text('Warmup browser website'),
                ),
                SizedBox(
                  height: 20,
                ),
                TextButton(
                  style: ElevatedButton.styleFrom(
                    primary: Colors.amber, // Background color
                    onPrimary: Colors.black, // Text color
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0), // Button border radius
                    ),
                  ),
                  onPressed: () => openBrowserTab(),
                  child: new Text('Open FlutterOne website'),
                ),
                SizedBox(
                  height: 20,
                ),
                TextButton(
                  style: ElevatedButton.styleFrom(
                    primary: Colors.black26, // Background color
                    onPrimary: Colors.white, // Text color
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0), // Button border radius
                    ),
                  ),
                  onPressed: () => openBrowserTab().then(
                    (value) => Future.delayed(
                      Duration(seconds: 5),
                      () => FlutterWebBrowser.close(),
                    ),
                  ),
                  child: new Text('Open Flutter website & close after 5 seconds'),
                ),
                SizedBox(
                  height: 20,
                ),
                if (Platform.isAndroid) ...[
                  Text('test Android customizations'),
                  TextButton(
                    style: ElevatedButton.styleFrom(
                      primary: Colors.lightBlueAccent, // Background color
                      onPrimary: Colors.white, // Text color
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.0), // Button border radius
                      ),
                    ),
                    onPressed: () {
                      FlutterWebBrowser.openWebPage(
                        url: "https://flutterone.com/",
                        customTabsOptions: CustomTabsOptions(
                          colorScheme: CustomTabsColorScheme.dark,
                          darkColorSchemeParams: CustomTabsColorSchemeParams(
                            toolbarColor: Colors.deepPurple,
                            secondaryToolbarColor: Colors.green,
                            navigationBarColor: Colors.amber,
                            navigationBarDividerColor: Colors.cyan,
                          ),
                          shareState: CustomTabsShareState.on,
                          instantAppsEnabled: true,
                          showTitle: true,
                          urlBarHidingEnabled: true,
                        ),
                      );
                    },
                    child: Text('Open Flutter website'),
                  ),
                ],
                if (Platform.isIOS) ...[
                  Text('test iOS customizations'),
                  TextButton(
                    onPressed: () {
                      FlutterWebBrowser.openWebPage(
                        url: "https://flutterone.com/",
                        safariVCOptions: SafariViewControllerOptions(
                          barCollapsingEnabled: true,
                          preferredBarTintColor: Colors.green,
                          preferredControlTintColor: Colors.amber,
                          dismissButtonStyle: SafariViewControllerDismissButtonStyle.close,
                          modalPresentationCapturesStatusBarAppearance: true,
                          modalPresentationStyle: UIModalPresentationStyle.popover,
                        ),
                      );
                    },
                    child: Text('Open Flutter website'),
                  ),
                  Divider(),
                  Column(
                    mainAxisSize: MainAxisSize.min,
                    children: _events.map((e) {
                      if (e is RedirectEvent) {
                        return Text('redirect: ${e.url}');
                      }
                      if (e is CloseEvent) {
                        return Text('closed');
                      }

                      return Text('Unknown event: $e');
                    }).toList(),
                  ),
                ]
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Output:

flutter web browser example app
Implementing a Web Browser in Flutter using flutter_web_browser Package ?
flutter web browser example ap
Implementing a Web Browser in Flutter using flutter_web_browser Package ?

Conclusion:

By following these steps, you can implement a web browser in your Flutter app using the flutter_web_browser package. This allows you to open web pages in the default browser from your Flutter app with ease.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *