I have managed to get a video to play on flutter-web, however, when I scroll the video in the ListView will rebuild/reload.
How can I stop the video_player (in the ListView) from being rebuilt when I scroll?
Sorry for the lengthy code sample.. I'm not sure how to condense it further
Any help would be great! Thanks
import 'package:flutter/material.dart';
import '../../widgets/video/chewie_video.dart';
import 'package:video_player/video_player.dart';
class TestPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
Container(height: 1000),
Center(
child: ChewieVideo(
videoPlayerController:
VideoPlayerController.asset('assets/video.mp4'),
),
),
Container(height: 1000),
],
),
);
}
}
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
class ChewieVideo extends StatefulWidget {
final VideoPlayerController videoPlayerController;
final bool looping;
ChewieVideo({
#required this.videoPlayerController,
this.looping,
Key key,
}) : super(key: key);
#override
_ChewieVideoState createState() => _ChewieVideoState();
}
class _ChewieVideoState extends State<ChewieVideo> {
ChewieController _chewieController;
#override
void initState() {
super.initState();
_chewieController = ChewieController(
videoPlayerController: widget.videoPlayerController,
autoInitialize: true,
aspectRatio: 16 / 9,
looping: widget.looping,
errorBuilder: (context, errorMessage) {
return Center(
child: Text(
errorMessage,
style: TextStyle(color: Colors.white),
),
);
},
);
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Chewie(
controller: _chewieController,
),
);
}
#override
void dispose() {
super.dispose();
widget.videoPlayerController.dispose();
_chewieController.dispose();
}
}
I'm not sure if this is a good or just temporary fix but this is how I have managed to get it to work...
If you are using inside of a ListView/CustomScrollView, then you need to adjust the cacheExtent for either of these widgets... I have set mine to 1000.
I'm not quite sure what's happening but it works...
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: primaryBlack,
drawer: NavDrawer(),
body: Scrollbar(
child: CustomScrollView(
cacheExtent: 1000,
slivers: <Widget>[
...
after doing that chewie and video_player plugins shouldn't rebuild/refresh inside of a ListView
Related
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'),
),
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,);
},
);
}
}
i want to create my portfolio using flutter web i use from page view to swipe between pages but page view not swiping this is my code i flow this guid but it not work for meFlutter PageView not swipeable on web (desktop mode)
class CustomPageView extends StatefulWidget {
const CustomPageView({Key? key}) : super(key: key);
#override
State<CustomPageView> createState() => _CustomPageViewState();
}
class _CustomPageViewState extends State<CustomPageView> {
var controller;
#override
void initState() {
controller = PageController(
initialPage: 0,
keepPage: true,
);
super.initState();
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: customAppBar(),
key: Globals.scaffoldKey,
endDrawer: const CustomEndDrawer(),
backgroundColor: whiteColor,
body: PageView(
controller: controller,
scrollDirection: Axis.vertical,
onPageChanged: (index) {
print(index);
},
// ignore: prefer_const_literals_to_create_immutables
children: [
const Home(),
Container(
color: Colors.red,
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
)
]),
);
}
}
By default none of the scrollable widgets are scrolled with mouse on web.
You can override the behavior by wrapping your widget a configuration.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
class MouseDraggableScrollBehavior extends MaterialScrollBehavior {
#override
Set<PointerDeviceKind> get dragDevices => <PointerDeviceKind>{
PointerDeviceKind.touch,
PointerDeviceKind.mouse,
};
}
After that wrap your PageView:
ScrollConfiguration(
behavior: MouseDraggableScrollBehavior(),
child: yourPageViewWidget,
)
LateInitializationError: Field '_latestValue#875205881' has not been initialized
Error image
I do not know what is the cause of the problem I tried to put ? Instead of late but there are still mistakes
Help me, thanks
video_screen.dart
import 'package:flutter/material.dart';
import '../screens/chewie_list_item.dart';
import 'package:chewie/chewie.dart';
import 'package:video_player/video_player.dart';
class VideoScreen extends StatefulWidget {
const VideoScreen({Key? key}) : super(key: key);
#override
_VideoScreenState createState() => _VideoScreenState();
}
class _VideoScreenState extends State<VideoScreen> {
ChewieController? _chewieController;
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
ChewieListItem(
videoPlayerController: VideoPlayerController.asset(
'videos/video1.mp4',
),
looping: true,
),
ChewieListItem(
videoPlayerController: VideoPlayerController.asset(
'videos/video2.mp4',
),
looping: true,
),
],
),
);
}
}
chewie_list_item.dart
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
class ChewieListItem extends StatefulWidget {
// This will contain the URL/asset path which we want to play
final VideoPlayerController videoPlayerController;
final bool looping;
ChewieListItem({
required this.videoPlayerController,
required this.looping,
Key? key,
}) : super(key: key);
#override
_ChewieListItemState createState() => _ChewieListItemState();
}
class _ChewieListItemState extends State<ChewieListItem> {
late ChewieController _chewieController;
#override
void initState() {
super.initState();
// Wrapper on top of the videoPlayerController
_chewieController = ChewieController(
videoPlayerController: widget.videoPlayerController,
aspectRatio: 16 / 9,
// Prepare the video to be played and display the first frame
autoInitialize: true,
looping: widget.looping,
// Errors can occur for example when trying to play a video
// from a non-existent URL
errorBuilder: (context, errorMessage) {
return Center(
child: Text(
errorMessage,
style: TextStyle(color: Colors.white),
),
);
},
);
}
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(8.0),
child: Chewie(
controller: _chewieController,
),
);
}
#override
void dispose() {
super.dispose();
// IMPORTANT to dispose of all the used resources
widget.videoPlayerController.dispose();
_chewieController.dispose();
}
}
I am getting below error while to implement YouTube video player in my flutter app.
Unhandled Exception: PlatformException(error, java.lang.IllegalStateException: Trying to create a platform view of unregistered type: com.pichillilorenzo/flutter_inappwebview.
how to solve this issue?
YoutubePlayerController controller = YoutubePlayerController(initialVideoId: youtubId);
YoutubePlayer(
controller: controller,
showVideoProgressIndicator: false,
progressIndicatorColor: AppColors.primaryColor,
);
I am using this package
Is there any other better way for playing youtube videos in flutter (apart from Webview)?
import 'package:cooking_genie/src/presentation/core/app_colors.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
class YoutubePlayerWidget extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return YoutubePlayerWidgetState();
}
}
class YoutubePlayerWidgetState extends State<YoutubePlayerWidget> {
//late YoutubePlayerController _controller;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return YoutubePlayer(
controller: YoutubePlayerController(
initialVideoId: 'zn2GwbPG-tc', //Add videoID.
flags: YoutubePlayerFlags(
hideControls: false,
controlsVisibleAtStart: true,
autoPlay: false,
mute: false,
),
),
showVideoProgressIndicator: true,
progressIndicatorColor: AppColors.primaryColor,
);
}
#override
void dispose() {
super.dispose();
}
}
///
class Controls extends StatelessWidget {
///
const Controls();
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_space,
],
),
);
}
Widget get _space => const SizedBox(height: 10);
}
check this widget. and make sure to change minSdkVersion 22 on andorid>app>build.gradle. package require >=17 for android.
import 'package:flutter/material.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
class YTplayerCheck extends StatefulWidget {
YTplayerCheck({Key? key}) : super(key: key);
#override
_YTplayerCheckState createState() => _YTplayerCheckState();
}
class _YTplayerCheckState extends State<YTplayerCheck> {
YoutubePlayerController controller = YoutubePlayerController(
initialVideoId: 'iLnmTe5Q2Qw',
flags: YoutubePlayerFlags(
autoPlay: true,
mute: true,
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
body: YoutubePlayer(
controller: controller,
showVideoProgressIndicator: false,
progressIndicatorColor: Colors.cyanAccent,
),
);
}
}