how to play video from video path in flutter - flutter

I get a list of video files now I want to play the video using path, for example, video path is 'storage/emulated/0/vedio1.mp4'. how can I play it? now.

with video_player package with that controller VideoPlayerController.file(...
https://pub.dev/documentation/video_player/latest/video_player/VideoPlayerController/VideoPlayerController.file.html

Use flutter's video_player
Example:
class _ButterFlyAssetVideo extends StatefulWidget {
#override
_ButterFlyAssetVideoState createState() => _ButterFlyAssetVideoState();
}
class _ButterFlyAssetVideoState extends State<_ButterFlyAssetVideo> {
late VideoPlayerController _controller;
#override
void initState() {
super.initState();
_controller = VideoPlayerController.asset('assets/Butterfly-209.mp4');
_controller.addListener(() {
setState(() {});
});
_controller.setLooping(true);
_controller.initialize().then((_) => setState(() {}));
_controller.play();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.only(top: 20.0),
),
const Text('With assets mp4'),
Container(
padding: const EdgeInsets.all(20),
child: AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
VideoPlayer(_controller),
_ControlsOverlay(controller: _controller),
VideoProgressIndicator(_controller, allowScrubbing: true),
],
),
),
),
],
),
);
}
}
Refer Flutter CookBook

// Inject video_player & chewie dependencies in your pubspec.yaml
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:chewie/chewie.dart';
import 'package:video_player/video_player.dart';
class ChewiePlayer extends StatefulWidget {
static const routeName = '/VideoScreen';
final File? videoUrl;
final String? dimension; //1920*1080
const ChewiePlayer({this.videoUrl, this.dimension,});
#override
State<ChewiePlayer> createState() => _ChewiePlayerState();
}
class _ChewiePlayerState extends State<ChewiePlayer> {
VideoPlayerController? _controller;
ChewieController? chewieController;
#override
void initState() {
initialize();
super.initState();
}
#override
void dispose() {
print('VideoScreen dispose');
chewieController?.videoPlayerController.dispose();
chewieController?.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child: Center(
child: AspectRatio(
aspectRatio: _controller!.value.aspectRatio,
child: Chewie(controller: chewieController!),
),
),
),
);
}
Future<void> initialize() async {
_controller = VideoPlayerController.file(widget.videoUrl!);
/// you can also play network and asset video, than declare accordingly example: VideoPlayerController.network( paste your link )
await _controller!.initialize().then((value) => setState(() {}));
chewieController = ChewieController(
videoPlayerController: _controller!,
autoInitialize: false,
autoPlay: false,
allowPlaybackSpeedChanging: true,
materialProgressColors:
ChewieProgressColors(playedColor: Colors.blue, handleColor: Colors.blue, bufferedColor: Colors.grey),
looping: false,
errorBuilder: (context, errorMessage) {
return Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(errorMessage, style: const TextStyle(color: Colors.white)),
),
);
},
);
}
}
// And use like this...
SizedBox(
child: ChewiePlayer(videoUrl: File(filePath), dimension: '1920*1080'),
),

Related

Data not loading after using annimation

I am making a chat app using flutter. It is loading data from firestore but when I am using annimation in the drawer the chat's aren't loading I don't know the reason if i comment out the animation in the chat screen it works and it works also if comment out if block which contain connection state.waiting without commenting annimation
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_app/chat/messages.dart';
import 'package:my_flutter_app/chat/new_message.dart';
class ChatScreen extends StatefulWidget {
const ChatScreen({Key? key}) : super(key: key);
#override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> with SingleTickerProviderStateMixin{
late AnimationController controller;
late Animation animation;
#override
void initState() {
super.initState();
controller=AnimationController(
duration: Duration(seconds: 2),
vsync: this);
animation=CurvedAnimation(parent: controller, curve: Curves.decelerate);
controller.forward();
animation.addStatusListener((status) {
if(status==AnimationStatus.completed){
controller.reverse(from: 1.0);
}else if(status==AnimationStatus.dismissed){
controller.forward();
}
});
controller.addListener(() {
setState(() {
animation.value;
});
});
}
#override
void dispose() {
super.dispose();
controller.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
margin: EdgeInsets.only(top: 50),
padding: EdgeInsets.all(15),
child: CircleAvatar(backgroundImage: AssetImage('assets/profile.png'),radius: 60),),
Container(
child: Image.asset('assets/welcome.png'),
height: animation.value*100,
),
InkWell(
onTap: (){
showCupertinoDialog(context: context, builder: (context)=>CupertinoAlertDialog(
title: Text('Alert'),
content: Text('Are you sure you want to logout?'),
actions: [
CupertinoDialogAction(child: Text('Yes'),onPressed: (){
FirebaseAuth.instance.signOut();
Navigator.pop(context);
},),
CupertinoDialogAction(child: Text('No'),onPressed: (){
Navigator.pop(context);
},)
],
));
//FirebaseAuth.instance.signOut();
},
child: ListTile(leading: Icon(Icons.logout,color: Colors.white),
title: Text('LOGOUT',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
tileColor: Colors.red,),
)
],
),
),
appBar: AppBar(title: Text('Chats'),centerTitle: true,backgroundColor: Colors.green),
body: Container(
child: Column(
children: [
Expanded(child: Messages()),
NewMessage(),
],
),
),
);
}
}
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_app/chat/mesui.dart';
class Messages extends StatefulWidget {
const Messages({Key? key}) : super(key: key);
#override
State<Messages> createState() => _MessagesState();
}
class _MessagesState extends State<Messages> {
final auth=FirebaseAuth.instance;
User ?cuser;
#override
void initState() {
// TODO: implement initState
super.initState();
getCurrentUser();
}
void getCurrentUser(){
try {
final user = auth.currentUser;
if (user != null) {
cuser = user;
}
}
catch(e){
print(e);
}
}
#override
Widget build(BuildContext context) {
return StreamBuilder(stream: FirebaseFirestore.instance.collection('chat').orderBy('messaged_on',descending: true).snapshots(),
builder: (context,snaps) {
if(snaps.connectionState == ConnectionState.waiting){
return Center(
child: CircularProgressIndicator(),
);
}
final documents=snaps.data!.docs;
final nowperson=cuser!.email;
return ListView.builder(
reverse: true,
itemBuilder: (ctx,index){
final sender=documents[index]['email'];
bool isMe= sender==nowperson;
return Mesui(documents[index]['text'],isMe);
},
itemCount: documents.length,);
},
);
}
}

Flutter youtube player iframe not working properly with full screen

I am using youtube_player_iframe to play you tube video. It is working but if click the full screen button on player, It is only show small as shown in picture. It is not always happen but It is happen once in two to three time.
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:thitsarparami/blocs/bloc.dart';
import 'package:thitsarparami/helper/constants.dart';
import 'package:thitsarparami/helper/enum.dart';
import 'package:thitsarparami/ui/error/something_went_wrong.dart';
import 'package:thitsarparami/widgets/circular_progress_indicator_widget.dart';
import 'package:youtube_player_iframe/youtube_player_iframe.dart';
class VideoScreen extends StatefulWidget {
static const routeName = '/video';
const VideoScreen({Key? key}) : super(key: key);
#override
_VideoScreenState createState() => _VideoScreenState();
}
class _VideoScreenState extends State<VideoScreen> {
#override
void initState() {
super.initState();
_loadYoutube();
}
_loadYoutube() async {
List<String> codes = [
systemDataCodeToString(SystemDataCode.youtube_live),
];
BlocProvider.of<SystemDataBloc>(context).add(GetYoutubeLiveEvent(codes));
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
elevation: 0,
title: AutoSizeText(
kYouTubeChannel,
style: Theme.of(context).appBarTheme.titleTextStyle,
),
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(
Icons.arrow_back,
color: Theme.of(context).primaryIconTheme.color!,
),
),
),
body: BlocBuilder<SystemDataBloc, SystemDataState>(
builder: (context, state) {
if (state is SystemDataError) {
return const SomethingWentWrongScreen();
} else if (state is YoutubeLiveDataLoaded) {
return Column(
mainAxisSize: MainAxisSize.max,
children: [
MyYoutubePlayer(
videoId: state.systemData.youtubeLive!.videoId!,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
state.systemData.youtubeLive!.videoTitle!,
style: const TextStyle(
color: Colors.black,
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
)
],
);
}
return const CircularProgressIndicatorWidget();
},
),
);
}
}
class MyYoutubePlayer extends StatefulWidget {
final String videoId;
const MyYoutubePlayer({Key? key, required this.videoId}) : super(key: key);
#override
State<MyYoutubePlayer> createState() => _MyYoutubePlayerState();
}
class _MyYoutubePlayerState extends State<MyYoutubePlayer> {
late YoutubePlayerController _controller;
#override
void initState() {
super.initState();
_controller = YoutubePlayerController(
initialVideoId: widget.videoId,
params: const YoutubePlayerParams(
showControls: true,
showFullscreenButton: true,
desktopMode: false,
privacyEnhanced: true,
useHybridComposition: true,
),
);
_controller.onEnterFullscreen = () {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
};
_controller.onExitFullscreen = () {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
};
}
#override
void dispose() {
_controller.close();
super.dispose();
}
#override
Widget build(BuildContext context) {
return YoutubePlayerIFrame(
controller: _controller,
aspectRatio: 16 / 9,
);
}
}
change this
Widget build(BuildContext context) {
return YoutubePlayerIFrame(
controller: _controller,
aspectRatio: 16 / 9,
);
}
to this
Widget build(BuildContext context) {
return YoutubePlayerScaffold(
autoFullScreen: true,
builder: ((context, player) {
return Container(
width: 100.w,
height: 100.h,
color: Colors.black,
child: Center(
child: player,
),
);
}),
controller: _controller
);
}
Fullscreen only works with YoutubePlayerScaffold Widget

How to check remote broadcast and fix error with videoplayer chewie in Flutter?

My English is not very good,
I have prepared an application to watch TV broadcasts with IP, broadcasts are coming, there is no problem, I watch the broadcast, when I switch to another broadcast, it crashes on the broadcast that does not come.
I want to check the incoming publication in the code written here, so that it does not give an error when the publication does not come, it returns to the main page or it can be written in the article as if this publication does not exist. Thanks
class ChewieVideo extends GetxController {
final String videoData;
ChewieVideo({required this.videoData});
late VideoPlayerController videoPlayerController;
ChewieController? chewieController;
#override
void onClose() {
super.onClose();
videoPlayerController.dispose();
chewieController!.dispose();
}
#override
void onInit() {
super.onInit();
initializePlayer();
}
Future<void> initializePlayer() async {
videoPlayerController = VideoPlayerController.network(videoData);
await Future.wait([videoPlayerController.initialize()]);
chewieController = (ChewieController(
videoPlayerController: videoPlayerController,
autoPlay: true,
looping: true,
materialProgressColors: ChewieProgressColors(
playedColor: Colors.red,
handleColor: Colors.cyanAccent,
backgroundColor: Colors.yellow,
bufferedColor: Colors.lightGreen,
),
placeholder: Container(
color: Colors.white,
),
autoInitialize: true,
errorBuilder: (context, errorMessage) {
return Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
errorMessage,
style: TextStyle(color: white),
),
),
);
}));
update();
}
}
class VideoApp extends StatefulWidget {
const VideoApp(
{Key? key, required this.videoData, required this.channelLoading})
: super(key: key);
final String videoData;
final String channelLoading;
#override
State<VideoApp> createState() => _VideoAppState();
}
class _VideoAppState extends State<VideoApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
GetBuilder<ChewieVideo>(
init: ChewieVideo(videoData: widget.videoData),
builder: (controller) => Expanded(
child: Center(
child: controller.chewieController != null &&
controller.chewieController!.videoPlayerController.value
.isInitialized
? Chewie(controller: controller.chewieController!)
: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(height: 10),
Text(
'${widget.channelLoading}=> Yükleniyor',
style: TextStyle(fontSize: 20),
),
],
),
),
),
),
],
),
);
}
}

getting error of Videoplayercontroller was used after being disposed in flutter when pressed back button

I am playing only one video in fullscreen landscape mode using Chewie video package. I am getting issue of videoplayercontroller was used after being disposed when i press back button of mobile. Firstly i disposed my chewiecontroller and then dispose videocontroller in dispose method but still i getting this issue. I don't able to find what is the problem so i get the error on back button pressed.Below is my code...
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
import 'package:newrit/main.dart';
import 'package:wakelock/wakelock.dart';
class StoryVideoPlayer extends StatefulWidget {
final String video_url;
const StoryVideoPlayer({Key key, this.video_url}) : super(key: key);
#override
_StoryVideoPlayerState createState() => _StoryVideoPlayerState(video_url);
}
class _StoryVideoPlayerState extends State<StoryVideoPlayer> {
final String video_url;
_StoryVideoPlayerState(this.video_url);
VideoPlayerController controller;
ChewieController _chewieController;
#override
void initState() {
// TODO: implement initState
super.initState();
Wakelock.enable();
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
print('video_url: $video_url');
controller = VideoPlayerController.network(video_url);
controller.addListener(() {
setState(() {});
checkVideo();
});
_chewieController = ChewieController(
videoPlayerController: controller,
allowFullScreen: false,
allowMuting: false,
fullScreenByDefault: true,
looping: false,
autoPlay: true,
allowedScreenSleep: false,
deviceOrientationsAfterFullScreen: const [
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
],
);
}
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
return WillPopScope(
onWillPop: (){
Navigator.pop(context, true);
},
child: SafeArea(
child: Scaffold(
body: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
Chewie(
controller: _chewieController,
),
Align(
alignment: FractionalOffset.topLeft,
child: Padding(
padding: const EdgeInsets.only(left: 15.0, top: 15.0),
child: Material(
type: MaterialType.transparency, //Makes it usable on any background color, thanks #IanSmith
child: Ink(
decoration: BoxDecoration(
border: Border.all(color: Colors.white, width: 4.0),
shape: BoxShape.circle,
),
child: InkWell(
onTap: () => Navigator.pop(context, true),
child: Padding(
padding: const EdgeInsets.fromLTRB(5.0,5.0,7.0,5.0),
child: Icon(Icons.arrow_back_ios,
size: useMobileLayout ? 22.0 : 35.0, color: Colors.white,),
)),
),
),
),
),
],
),
),
),
);
}
void checkVideo() {
if(controller.value.position == Duration(seconds: 0, minutes: 0, hours: 0)) {
}
if(controller.value.position == controller.value.duration) {
print('video Ended');
}
}
#override
void dispose() {
_dispose();
super.dispose();
}
void _dispose() async{
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
_chewieController.dispose();
await controller.dispose();
Wakelock.disable();
}
}

How do you change the VideoPlayer Fullscreen Mode to Landscape instead of Portrait

I want my videoplayer fullscreen to be in landscape mode when entering Full Screen.
You can copy paste run full code below
You can use package https://pub.dev/packages/auto_orientation and https://pub.dev/packages/chewie
In initState() of _VideoScaffoldState do AutoOrientation.landscapeAutoMode();
code snippet
_chewieController = ChewieController(
videoPlayerController: _videoPlayerController1,
aspectRatio: 3 / 2,
autoPlay: true,
looping: true,
routePageBuilder: (BuildContext context, Animation<double> animation,
Animation<double> secondAnimation, provider) {
return AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget child) {
return VideoScaffold(
...
class _VideoScaffoldState extends State<VideoScaffold> {
#override
void initState() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
AutoOrientation.landscapeAutoMode();
super.initState();
}
working demo
full code
import 'package:auto_orientation/auto_orientation.dart';
import 'package:chewie/chewie.dart';
import 'package:chewie/src/chewie_player.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
void main() {
runApp(
ChewieDemo(),
);
}
class ChewieDemo extends StatefulWidget {
ChewieDemo({this.title = 'Chewie Demo'});
final String title;
#override
State<StatefulWidget> createState() {
return _ChewieDemoState();
}
}
class _ChewieDemoState extends State<ChewieDemo> {
TargetPlatform _platform;
VideoPlayerController _videoPlayerController1;
VideoPlayerController _videoPlayerController2;
ChewieController _chewieController;
#override
void initState() {
super.initState();
_videoPlayerController1 = VideoPlayerController.network(
'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4');
_videoPlayerController2 = VideoPlayerController.network(
'https://www.sample-videos.com/video123/mp4/480/big_buck_bunny_480p_20mb.mp4');
_chewieController = ChewieController(
videoPlayerController: _videoPlayerController1,
aspectRatio: 3 / 2,
autoPlay: true,
looping: true,
routePageBuilder: (BuildContext context, Animation<double> animation,
Animation<double> secondAnimation, provider) {
return AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget child) {
return VideoScaffold(
child: Scaffold(
resizeToAvoidBottomPadding: false,
body: Container(
alignment: Alignment.center,
color: Colors.black,
child: provider,
),
),
);
},
);
}
// Try playing around with some of these other options:
// showControls: false,
// materialProgressColors: ChewieProgressColors(
// playedColor: Colors.red,
// handleColor: Colors.blue,
// backgroundColor: Colors.grey,
// bufferedColor: Colors.lightGreen,
// ),
// placeholder: Container(
// color: Colors.grey,
// ),
// autoInitialize: true,
);
}
#override
void dispose() {
_videoPlayerController1.dispose();
_videoPlayerController2.dispose();
_chewieController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: widget.title,
theme: ThemeData.light().copyWith(
platform: _platform ?? Theme.of(context).platform,
),
home: Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: <Widget>[
Expanded(
child: Center(
child: Chewie(
controller: _chewieController,
),
),
),
FlatButton(
onPressed: () {
_chewieController.enterFullScreen();
},
child: Text('Fullscreen'),
),
Row(
children: <Widget>[
Expanded(
child: FlatButton(
onPressed: () {
setState(() {
_chewieController.dispose();
_videoPlayerController2.pause();
_videoPlayerController2.seekTo(Duration(seconds: 0));
_chewieController = ChewieController(
videoPlayerController: _videoPlayerController1,
aspectRatio: 3 / 2,
autoPlay: true,
looping: true,
);
});
},
child: Padding(
child: Text("Video 1"),
padding: EdgeInsets.symmetric(vertical: 16.0),
),
),
),
Expanded(
child: FlatButton(
onPressed: () {
setState(() {
_chewieController.dispose();
_videoPlayerController1.pause();
_videoPlayerController1.seekTo(Duration(seconds: 0));
_chewieController = ChewieController(
videoPlayerController: _videoPlayerController2,
aspectRatio: 3 / 2,
autoPlay: true,
looping: true,
);
});
},
child: Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Text("Video 2"),
),
),
)
],
),
Row(
children: <Widget>[
Expanded(
child: FlatButton(
onPressed: () {
setState(() {
_platform = TargetPlatform.android;
});
},
child: Padding(
child: Text("Android controls"),
padding: EdgeInsets.symmetric(vertical: 16.0),
),
),
),
Expanded(
child: FlatButton(
onPressed: () {
setState(() {
_platform = TargetPlatform.iOS;
});
},
child: Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Text("iOS controls"),
),
),
)
],
)
],
),
),
);
}
}
class VideoScaffold extends StatefulWidget {
const VideoScaffold({Key key, this.child}) : super(key: key);
final Widget child;
#override
State<StatefulWidget> createState() => _VideoScaffoldState();
}
class _VideoScaffoldState extends State<VideoScaffold> {
#override
void initState() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
AutoOrientation.landscapeAutoMode();
super.initState();
}
#override
dispose() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
AutoOrientation.portraitAutoMode();
super.dispose();
}
#override
Widget build(BuildContext context) {
return widget.child;
}
}
If I understood correctly then -
You can create an event on the fullscreen icon(assuming you have an icon to identify fullscreen mode) and take leverage of flutter's OrientationBuilder widget.
A sample would be like below code, which I used for my own project. Please note key, backgroundColor properties are not required for OrientationBuilder widget. It was my project requirements.
return Scaffold(
key: _homeKey,
backgroundColor: bodyBackground,
body: OrientationBuilder(
builder: (context, orientation) {
return Container(
child: orientation == Orientation.portrait
? _potraitView()
: _landscapeView(),
);
},
),
);
You can then create your own widget inside _landscapeView() (for example) return may be a Container with width an height to fit the screen.
Something like
Widget _landscapeView() {
return Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: <Your design specs>
);
Hope that will help !!
Good luck