我尝试了几个在 Flutter 桌面应用程序中播放 YouTube 视频的包,包括 Web 视图和 HTML 包,但没有一个起作用。我需要一个可靠的解决方案来嵌入 YouTube 内容。
如果您使用桌面 Flutter 应用程序,会有所帮助。
将 youtube_player_flutter 包添加到您的 pubspec.yaml 文件中:
dependencies:
youtube_player_flutter: ^8.1.2
尝试这个代码:
import 'package:flutter/material.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: YouTubePlayerScreen(),
);
}
}
class YouTubePlayerScreen extends StatefulWidget {
@override
_YouTubePlayerScreenState createState() => _YouTubePlayerScreenState();
}
class _YouTubePlayerScreenState extends State<YouTubePlayerScreen> {
late YoutubePlayerController _controller;
@override
void initState() {
super.initState();
_controller = YoutubePlayerController(
initialVideoId: 'dQw4w9WgXcQ', // Replace with your video ID
flags: YoutubePlayerFlags(
autoPlay: true,
mute: false,
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('YouTube Player'),
),
body: YoutubePlayer(
controller: _controller,
showVideoProgressIndicator: true,
progressIndicatorColor: Colors.amber,
onReady: () {
print('Player is ready.');
},
),
);
}
}
试试这个