I'm using youtube_player_iframe package for flutter web. The issue I'm facing is that if I start playing a youtube video and then go to another screen, the video is still playing in the background.
I've included the dispose and close of the controller, but it doesn't work.
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:youtube_player_iframe/youtube_player_iframe.dart';
class AddYoutubeVideo extends StatefulWidget {
final String videoUrl;
const AddYoutubeVideo({Key? key, required this.videoUrl}) : super(key: key);
@override
State<AddYoutubeVideo> createState() => _AddYoutubeVideoState();
}
class _AddYoutubeVideoState extends State<AddYoutubeVideo> {
late YoutubePlayerController _youtubeController;
@override
void initState() {
super.initState();
_youtubeController = YoutubePlayerController(
initialVideoId: YoutubePlayerController.convertUrlToId(widget.videoUrl)!,
params: const YoutubePlayerParams(
showControls: true,
showFullscreenButton: true,
autoPlay: false,
),
);
_youtubeController.onEnterFullscreen = () {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
};
}
@override
void dispose() {
super.dispose(); // Have tried to use super.dispose below the close() also
_youtubeController.close();
}
@override
Widget build(BuildContext context) {
return YoutubePlayerIFrame(
controller: _youtubeController,
aspectRatio: 16 / 9,
);
}
}
I'm then using this class to display two youtube videos simply with:
AddYoutubeVideo(videoUrl: url1)),
Is there anything that I've done wrong or should have been doing instead?
By moving to the next screen I assume that you are performing Navigator.push or Navigator.pushNamed
On both the cases the screen stays at the stack and will definitely play at the background. If you are moving to another screen. You can try
Navigator.pushReplacement
//or
Navigator.pushReplacementNamed
//or to go to Previous screen you can pop the current screen
Navigator.pop(context);
In all the 3 cases the dispose is called.