我想在网页视图数据显示在屏幕上之前先显示正在加载。如何使用 flutter_inappwebview 包做到这一点?
这是我的代码:
home: Scaffold(
body: Stack(
children: [
isLoading
? const Center(child: CircularProgressIndicator())
: const SizedBox(),
Column(
children: [
const SizedBox(height: 30),
Expanded(
child: InAppWebView(
key: _key,
onLoadStop: (controller, url) {
setState(() {
isLoading = false;
});
},
initialUrlRequest: URLRequest(
url: Uri.parse('https://example.com/')),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
mediaPlaybackRequiresUserGesture: false,
),
),
androidOnPermissionRequest:
(InAppWebViewController controller, String origin,
List<String> resources) async {
return PermissionRequestResponse(
resources: resources,
action: PermissionRequestResponseAction.GRANT,
);
},
),
),
],
)
],
),
)
添加@user18309290答案:
确保
Stack
中出现的小部件的顺序正确。我的第二个问题是 InAppWebView
(覆盖整个屏幕)位于我的 CircularProgressIndicator
小部件上方。重新排序小部件的 Stack
解决了这个问题。
这是正确的工作代码:
Stack(
children: [
isLoading
? const Center(child: CircularProgressIndicator())
: const SizedBox(),
Column(
children: [
const SizedBox(height: 30),
Expanded(
child: InAppWebView(
key: _key,
onLoadStop: (controller, url) {
setState(() {
isLoading = false;
});
},
initialUrlRequest: URLRequest(
url: Uri.parse('https://example.com/')),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
mediaPlaybackRequiresUserGesture: false,
),
),
androidOnPermissionRequest:
(InAppWebViewController controller, String origin,
List<String> resources) async {
return PermissionRequestResponse(
resources: resources,
action: PermissionRequestResponseAction.GRANT,
);
},
),
),
],
)
],
),
在版本 6.x 中,使用 Stack 将加载指示器放置在 InAppWebView 的顶部。然后 onProgressChanged 来控制加载指示器的可见性。
ExemplePage 类扩展 StatefulWidget {
@override
State<ExemplePage> createState() => _ExemplePageState();
}
class _ExemplePageState extends State<ExemplePage> {
bool showLoading = true;
@override
Widget build(BuildContext context) {
return Material(
child: Stack(
children: [
InAppWebView(
initialData: InAppWebViewInitialData(
data: '<html></html>',
),
onProgressChanged: (_, progress) {
if (progress >= 100) {
setState(() {
showLoading = false;
});
}
},
),
if (showLoading) CircularProgressIndicator(),
],
),
);
}
}