使用 Flutter 中的 WebView 时,切换页面时可能会出现黑屏或闪屏的问题,使用一个带有加载动画的页面来代替黑屏。在 WebView 加载新页面时,显示一个带有加载动画的页面,等到 WebView 加载完毕后再将其隐藏。
时间: 2024-02-21 13:56:38 浏览: 19
好的,针对您的问题,我可以给出一个示例代码来实现在 Flutter 中使用 WebView 时显示加载动画的效果。
首先,我们需要使用 `flutter_inappwebview` 插件来实现 WebView 的功能。在 `pubspec.yaml` 文件中添加以下依赖项:
```yaml
dependencies:
flutter_inappwebview: ^5.3.2
```
接下来,我们可以创建一个新的 StatefulWidget,其中包含一个 WebView 和一个带有加载动画的页面。这里我们使用前置条件来判断 WebView 是否在加载,如果是,则显示加载动画页面,否则显示 WebView。
```dart
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
class WebViewExample extends StatefulWidget {
final String initialUrl;
WebViewExample({this.initialUrl});
@override
_WebViewExampleState createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<WebViewExample> {
InAppWebViewController _webViewController;
bool _isLoading = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
InAppWebView(
initialUrl: widget.initialUrl,
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
javaScriptEnabled: true,
),
),
onWebViewCreated: (InAppWebViewController controller) {
_webViewController = controller;
},
onLoadStart: (InAppWebViewController controller, String url) {
setState(() {
_isLoading = true;
});
},
onLoadStop: (InAppWebViewController controller, String url) {
setState(() {
_isLoading = false;
});
},
),
_isLoading
? Container(
color: Colors.white,
child: Center(
child: CircularProgressIndicator(),
),
)
: Container(),
],
),
);
}
}
```
在上面的示例代码中,我们使用了 `Stack` 组件来同时显示 WebView 和加载动画页面。当 WebView 开始加载时,`onLoadStart` 回调函数会被调用,我们在这里将 `_isLoading` 状态设置为 `true`,以便显示加载动画页面。当 WebView 加载完成时,`onLoadStop` 回调函数会被调用,我们在这里将 `_isLoading` 状态设置为 `false`,以便隐藏加载动画页面。
希望这个示例代码可以帮助到您。