How to Use a Web View in Flutter

Last update: 06-11-2024

In this blog post, we will explore Flutter's built-in WebView, a very versatile and useful tool for displaying web content within your Flutter application. By leveraging WebView, you can create a simple web browser that integrates seamlessly with your Flutter app, allowing you to display websites, web pages, or any web content you need. This feature is particularly beneficial for apps that require embedded web pages or need to interact with online content directly.


To create a web view in Flutter, we primarily need the WebViewWidget. The WebViewWidget behaves like any ordinary widget, so wherever you might place, for example, an ElevatedButton widget, you can place a WebViewWidget.

The WebViewWidget requires a parameter of type WebViewController, and this controller is what we use to navigate to a web page. We simply call the controller's loadRequest function to load the web page we want, and it will be displayed in the WebViewWidget.

In the example below, upon submitting a URL, we call the controller's loadRequest function to update the web page shown in the WebViewWidget.

Flutter Web view


Make sure you have the webview dependency in your pubspec.yaml file, and don't forget to run pub get to fetch the dependencies.


dependencies:
  flutter:
    sdk: flutter
  webview_flutter: ^4.8.0

Full Example:


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

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

class WebViewContainer extends StatefulWidget {
  const WebViewContainer({super.key});

  @override
  State createState() => _WebViewContainerState();
}

class _WebViewContainerState extends State {
  final webViewController = WebViewController();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextField(
          style: const TextStyle(fontSize: 30, color: Colors.purple),
          onSubmitted: (value) {
            webViewController.loadRequest(Uri.parse('https://$value'));
          },
        ),
        Expanded(child: WebViewWidget(controller: webViewController))
      ],
    );
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: const Text("Web View"),
          ),
          body: WebViewContainer()),
    );
  }
}

In this example:

By following this approach, you can create a simple and functional web browser within your Flutter application, providing an intuitive way for users to interact with web content directly from your app.

StocksComparison.com ad
 

0 Comments

Add a new comment: