乐闻世界logo
搜索文章和话题

Flutter : How to show a CircularProgressIndicator before WebView loads the page?

1个答案

1

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:

  1. Introduce Dependencies: First, ensure that your pubspec.yaml file includes a WebView plugin such as flutter_webview_plugin or webview_flutter.

  2. Create a New Flutter App: In your app, create a new screen or component to display the WebView.

  3. Use Stack and Visibility Widgets: Use the Stack to overlay the WebView and the CircularProgressIndicator, and use a boolean state variable to control the visibility of the loading indicator.

Here is an example code snippet:

dart
import '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 _isLoading variable tracks whether the webpage is loading.
  • The WebView's onPageFinished event is used to listen for when the page finishes loading and updates the _isLoading state.
  • The Stack widget allows the CircularProgressIndicator to be overlaid on top of the WebView, 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.

2024年8月8日 14:11 回复

你的答案