lundi 30 août 2021

How to use if condition in initState() method while using YouTube video player and simple video player? I am also using Provider package

I am using a Youtube video player to play youtube links and a simple video player to play uploaded videos. I want to use the if statement in the InitState method, because without using it, I am unable to play Youtube videos. (I basically want to play videos of both types). Can anyone please help using it? Below is my code.

class VideoBox extends StatefulWidget {
  @override
  _VideoBoxState createState() => _VideoBoxState();
}

class _VideoBoxState extends State<VideoBox> {
  YoutubePlayerController _controller;

  void runYoutubePlayer() {
    final testdata = Provider.of<VideosModel>(context, listen: false);

    _controller = YoutubePlayerController(
        initialVideoId: YoutubePlayer.convertUrlToId(testdata.link),
        flags: YoutubePlayerFlags(
          enableCaption: false,
          autoPlay: false,
          isLive: false,
        ));
  }

  @override
  void initState() {
    final testData = Provider.of<VideosModel>(context, listen: false);

    if (testData.link != null) {
      runYoutubePlayer();
    }

    super.initState();
  }

  @override
  void deactivate() {
    _controller.pause();
    super.deactivate();
  }

  @override
  void dispose() {
    _controller.dispose();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final testData = Provider.of<VideosModel>(context, listen: false);

    if (testData.video == null) {
      return YoutubePlayerBuilder(
        player: YoutubePlayer(
          controller: _controller,
        ),
        builder: (context, player) {
          return Container(
            height: 24.0.h,
            width: 100.0.w,
            child: player,
          );
        },
      );
    } else {
      return Container(
          height: 24.0.h,
          width: 100.0.w,
          child: VideoItem(
              'https://hospitality92.com/uploads/videos/' + testData.video));
    }
  }
}

Aucun commentaire:

Enregistrer un commentaire