Showing posts with label web-view. Show all posts
Showing posts with label web-view. Show all posts

Wednesday, September 21, 2022

Web Views Open Website URL in Flutter Example & Output

For web view in flutter, we use webview_flutter, a Flutter package that provides a WebView widget on Android and iOS.

To get started, first add webview_flutter as a dependency in your pubspec.yaml file, like this:

webview_flutter: ^0.3.19+9

Incase you get this error Cannot run with sound null safety, because the following dependencies do

IDE run arguments/configuration

To set this up in your IDE of choice, you can use:

In IntelliJ/Android Studio: "Edit Configurations" (in your run configurations) → "Additional run args".

In Visual Studio Code: search for "Flutter run additional args" in your user settings.

In both cases, add --no-sound-null-safety.
After adding webview_flutter package, you can use WebView() widget. This widget has three basic arguments, thye're key, javascriptMode & initialUrl. See the implementation below:
Code Snippet: Web View Open Website URL in Flutter
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Web View URL Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Web View URL Example'),
          centerTitle: true,
        ),
        body: WebViewExample('https://www.google.com/'),
      ),
    );
  }
}

class WebViewExample extends StatefulWidget {
  final String url;
  WebViewExample(this.url);
  @override
  _WebViewExampleState createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<WebViewExample> {
  final _key = UniqueKey();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Expanded(
            child: WebView(
              key: _key,
              javascriptMode: JavascriptMode.unrestricted,
              initialUrl: widget.url,
            ),
          ),
        ],
      ),
    );
  }
}
Output: Web View Open Website URL in Flutter

For more details please see WebView for Flutter which has documentation for this package.