In Flutter, if you want to display a CircularProgressIndicator before the WebView loads, you can use the Stack widget to overlay the WebView with the CircularProgressIndicator and use a state variable to control when to show or hide the loading indicator. Here is a specific implementation example:
-
Introduce Dependencies: First, ensure that your
pubspec.yamlfile includes a WebView plugin such asflutter_webview_pluginorwebview_flutter. -
Create a New Flutter App: In your app, create a new screen or component to display the WebView.
-
Use Stack and Visibility Widgets: Use the
Stackto overlay theWebViewand theCircularProgressIndicator, and use a boolean state variable to control the visibility of the loading indicator.
Here is an example code snippet:
dartimport 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; class WebViewExample extends StatefulWidget { _WebViewExampleState createState() => _WebViewExampleState(); } class _WebViewExampleState extends State<WebViewExample> { bool _isLoading = true; // initial state where loading is in progress void _handlePageFinished(String url) { setState(() { _isLoading = false; // page loading complete, update state to hide the loading indicator }); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('WebView with Loader'), ), body: Stack( children: <Widget>[ WebView( initialUrl: 'https://www.example.com', onPageFinished: _handlePageFinished, ), _isLoading ? Center(child: CircularProgressIndicator()) // if loading, show loading indicator : Container(), // otherwise show empty container ], ), ); } }
In this code example:
- The
_isLoadingvariable tracks whether the webpage is loading. - The
WebView'sonPageFinishedevent is used to listen for when the page finishes loading and updates the_isLoadingstate. - The
Stackwidget allows theCircularProgressIndicatorto be overlaid on top of theWebView, showing while the page is loading and hiding once it finishes.
This way, users see a centered loading indicator while the WebView loads content, improving the user experience.