import 'package:video_player/video_player.dart'; import 'package:flutter/material.dart'; class VideoWidget extends StatefulWidget { VideoWidget({Key key, this.videoSrc}) : super(key: key); final String videoSrc; // 用来储存传递过来的值 @override VideoWidgetState createState() => VideoWidgetState(); } class VideoWidgetState extends State { VideoPlayerController _controller; String _defaultVideo = 'http://oss.izouma.com/shouyoudianjing/video/2019-03-01-11-19-41-ivqsgiy9.mp4'; bool isVideo = true; bool showVideo = false; bool isPlay = false; @override void initState() { super.initState(); if (widget.videoSrc == null) { } else { if (widget.videoSrc.contains('.mp4')) { _defaultVideo = widget.videoSrc; isVideo = true; } else { isVideo = false; } } if (isVideo) { _controller = VideoPlayerController.network(_defaultVideo) ..initialize().then((_) { // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed. setState(() {}); }); _controller.setLooping(true); _controller.addListener(() { setState(() { isPlay = _controller.value.isPlaying; }); // if(_controller.value.isLooping) }); } } @override void dispose() { super.dispose(); _controller.dispose(); } Future playVideo() async { if (!showVideo) { setState(() { showVideo = true; }); await Future.delayed(Duration(milliseconds: 500)); } _controller.value.isPlaying ? _controller.pause() : _controller.play(); } @override Widget build(BuildContext context) { return Container( child: Column( children: [ isVideo ? _playContainer() : Image.network( widget.videoSrc, width: double.infinity, height: 210, fit: BoxFit.cover, ) ], )); } Widget _playContainer() { return Container( color: Colors.black, height: 210, width: double.infinity, child: Center( child: Stack( children: [ InkWell( child: Center( child: showVideo ? AspectRatio( aspectRatio: _controller.value.aspectRatio, child: VideoPlayer(_controller), ) : Image.network( 'http://images.liqucn.com/img/h22/h70/img_localize_8e824debdd9ee29522690f36680e2d8e_600x337.png', width: double.infinity, fit: BoxFit.cover, ), ), onTap: () => playVideo()), !isPlay ? Positioned( left: 0, right: 0, top: 83, child: Center( child: UnconstrainedBox( child: Container( width: 44, height: 44, child: RaisedButton( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(44)), padding: EdgeInsets.all(0), color: Colors.black87, textColor: Colors.white, onPressed: () => playVideo(), child: Icon(isPlay ? Icons.pause : Icons.play_arrow), ), ), ), )) : Container(), ], ), ), ); // return InkWell( // child: AspectRatio( // aspectRatio: _controller.value.aspectRatio, // child: VideoPlayer(_controller), // ), // onTap: () { // _controller.value.isPlaying ? _controller.pause() : _controller.play(); // }, // ); } }