flutter webview 代码实现播放H5视频
时间: 2023-07-25 14:06:54 浏览: 331
在 Flutter 中,可以使用 `webview_flutter` 插件来实现加载 H5 视频的功能。下面是一个简单的示例代码:
```dart
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class VideoPlayer extends StatefulWidget {
final String url;
VideoPlayer({required this.url});
@override
_VideoPlayerState createState() => _VideoPlayerState();
}
class _VideoPlayerState extends State<VideoPlayer> {
late WebViewController _controller;
@override
Widget build(BuildContext context) {
return Scaffold(
body: WebView(
initialUrl: widget.url,
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller = webViewController;
},
onPageFinished: (String url) {
_controller.evaluateJavascript(
'document.getElementsByTagName("video")[0].play();');
},
),
);
}
}
```
这里我们创建了一个名为 `VideoPlayer` 的组件,并传入一个 `url` 参数来指定要播放的视频地址。在 `build` 方法中,我们返回一个 `WebView` 组件,并在其中设置了以下属性:
- `initialUrl`:指定要加载的初始网页地址,即 H5 视频的地址。
- `javascriptMode`:指定 WebView 中的 JavaScript 模式为不受限制的,以便我们可以执行自定义 JavaScript 代码。
- `onWebViewCreated`:当 WebView 创建完成后,我们将获取到的 `WebViewController` 对象保存在 `_controller` 属性中以便后续使用。
- `onPageFinished`:当 WebView 加载完成后,我们执行 JavaScript 代码来播放 H5 视频。在这里,我们通过 `document.getElementsByTagName("video")[0]` 获取到页面中的第一个视频元素,并调用其 `play()` 方法来开始播放视频。
这样,我们就可以在 Flutter 应用中使用 WebView 组件来播放 H5 视频了。
阅读全文
相关推荐


















