According to the Migrating from 3.0 to 4.0 section in the documentation
Migrating from 3.0 to 4.0 Instantiating WebViewController In version
3.0 and below, WebViewController could only be retrieved in a callback after the WebView was added to the widget tree. Now, WebViewController
must be instantiated and can be used before it is added to the widget
tree. See Usage section above for an example.
Replacing WebView Functionality The WebView class has been removed
and its functionality has been split into WebViewController and
WebViewWidget.
WebViewController handles all functionality that is associated with
the underlying web view provided by each platform. (e.g., loading a
url, setting the background color of the underlying platform view, or
clearing the cache).
WebViewWidget takes a WebViewController and handles all Flutter widget
related functionality (e.g., layout direction, gesture recognizers).
See the Dartdocs for WebViewController and WebViewWidget for more details.
Here a sample that you can use
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(
home: WebViewExample(),
);
}
}
class WebViewExample extends StatefulWidget {
@override
_WebViewExampleState createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<WebViewExample> {
late WebViewController webViewController;
@override
void initState() {
super.initState();
webViewController = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {},
onPageStarted: (String url) {},
onPageFinished: (String url) {},
onWebResourceError: (WebResourceError error) {},
onNavigationRequest: (NavigationRequest request) {
if (request.url.startsWith('https://www.youtube.com/')) {
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
),
)
..loadRequest(Uri.parse('https://flutter.dev'));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('WebView Example'),
),
body: WebViewWidget(
controller: webViewController,
),
);
}
}