Rohith Rathod
Rohith Rathod

Reputation: 3

How to restart video playback

I have a VideoPlayerItem widget that plays a video and triggers an onVideoEnd callback when the video ends. I also have a refresh button that I want to use to restart the video playback. How do I do this?

videoplayeritem

class VideoPlayerItem extends StatefulWidget {
  final String videoUrl;
  final Function onVideoEnd;
  const VideoPlayerItem({super.key, required this.videoUrl,required this.onVideoEnd});

  @override
  State<VideoPlayerItem> createState() => _VideoPlayerItemState();
}

class _VideoPlayerItemState extends State<VideoPlayerItem> {
  late VideoPlayerController videoPlayerController;

  @override
  void initState() {
    super.initState();
    videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(widget.videoUrl))
      ..initialize().then((_) {
        videoPlayerController.play();
        videoPlayerController.setVolume(1);
        setState(() {}); // Ensure the UI updates once initialized
      });
    videoPlayerController.addListener(() {
      if (videoPlayerController.value.position >= videoPlayerController.value.duration) {
        widget.onVideoEnd();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    videoPlayerController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Container(
      height: size.height,
      width: size.width,
      decoration: BoxDecoration(
        color: Colors.grey[200],
      ),
      child: VideoPlayer(videoPlayerController),
    );
  }
}

Initializing the VideoPlayerItem widget

Widget buildContent(Post post) {
  switch (post.type) {
    case 'video':
      return VideoPlayerItem(
        videoUrl: post.videoUrl!,
        onVideoEnd: () {
          setState(() {
            showRateOverlay = true;
          });
        },
      );
    // ...
  }
}

Refresh button code

InkWell(
  onTap: () {
    setState(() {
      showRateOverlay = false; // Hide the rate overlay
    });
    if (post.type == 'image' || post.type == 'text') {
      // Reset the timer
      _rateOverlayTimer?.cancel();
      _rateOverlayTimer = Timer(Duration(seconds: 8), () {
        setState(() {
          showRateOverlay = true; // Show the rate overlay after 15 seconds
        });
      });
    }
  },
  child: const Icon(
    Icons.refresh_outlined,
    size: 40,
    color: Colors.white,
  ),
),

I want it so that when I click on the refresh_outlined button, the video starts again, and when the video ends, the showRateOverlay state is true.

Upvotes: 0

Views: 29

Answers (0)

Related Questions