是否可以在flutter的无状态小部件中创建视频播放器?

wljmcqd8  于 2023-02-16  发布在  Flutter
关注(0)|答案(1)|浏览(103)

我试图在flutter中的无状态小部件中创建一个视频播放器。我做不到....这是我使用的代码...有可能在无状态小部件中创建一个视频播放器吗?

class VideoWidget extends StatelessWidget {
  VideoWidget({Key? key}) : super(key: key);
  final videoController =
      VideoPlayerController.network('https://youtu.be/_EoLNs5m-7Y?t=4')
        ..initialize();
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: MediaQuery.of(context).size.width,
      //height: 500,
      child: Column(
        children: [
          //VideoPlayer(videoController!),
          ValueListenableBuilder(
              valueListenable: videoPlayerNotifier,
              builder: (BuildContext cxt, play, widget_) {
                return videoController.value.isInitialized
                    ? AspectRatio(
                        aspectRatio: videoController.value.aspectRatio,
                        child: VideoPlayer(videoController))
                    : Container();
              }),

          const Text(
            'movieName',
             style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          const Text('Description'),
          FloatingActionButton(onPressed: () {
            videoPlayerNotifier.value = true;
          })
        ],
      ),
    );
  }
}
wnvonmuf

wnvonmuf1#

video_player pub包中的VideoPlayer是有状态的,特别是因为VideoPlayerController。但是,您可以将其 Package 在StatefulWidget中,以便在StatelessWidget中使用。例如,在无状态小部件中使用以下 Package 器:

class VideoPlayerWrapper extends StatefulWidget {
  final String videoUri;

  const VideoPlayerWrapper({Key? key, required this.videoUri}) : super(key: key);

  @override
  _VideoPlayerWrapperState createState() => _VideoPlayerWrapperState(videoUri);
}

class _VideoPlayerWrapperState extends State<VideoPlayerWrapper> {
  late VideoPlayerController _controller;
  final String videoUri;

  _VideoPlayerWrapperState(this.videoUri);

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(videoUri)
      ..initialize().then((_) {
        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
        setState(() {});
      });
    _controller.play();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
          child: _controller.value.isInitialized
              ? AspectRatio(
            aspectRatio: _controller.value.aspectRatio,
            child: VideoPlayer(_controller),
          )
              : Container(),
    );
  }

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

相关问题