How to print a video path in videoplayercontroller.asset() in flutter - flutter

So I was trying to make a feature where when we click an icon button it will change the video path. It will change the video path using string. I was using a print("$videoname"), to make sure the string changes, and it does. But it still doesn't work, with the videoplayercontroller.assets():
Here's the code that I was trying to make
String videoname="Video/Intro.mp4";
Container(
child:Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ChewieListItem(
videoPlayerController: VideoPlayerController.asset(videoname),
looping: false,
),
Container(
margin: EdgeInsets.symmetric(vertical: 20.0),
height: 100.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
IconButton(
icon:Icon(Icons.people),
onPressed: (){
videoname="Video/Intro.mp4";
print("$videoname");
},
),
IconButton(
icon:Icon(Icons.personal_video),
onPressed: (){
videoname="Video/Intro1.mp4";
print("$videoname");
},
),
],
),
),
)

You can copy paste run full code below
Step 1: Use key: UniqueKey() in ChewieListItem
Step 2: Use setState in onPressed
code snippet
ChewieListItem(
key: UniqueKey(),
videoPlayerController: VideoPlayerController.asset(videoname),
looping: false,
),
IconButton(
icon: Icon(Icons.people),
onPressed: () {
setState(() {
videoname = "Video/Intro.mp4";
print("$videoname");
});
},
),
IconButton(
icon: Icon(Icons.personal_video),
onPressed: () {
setState(() {
videoname = "Video/Intro1.mp4";
print("$videoname");
});
},
),
working demo
full code
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.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,
this.looping,
Key key,
}) : super(key: key);
#override
_ChewieListItemState createState() => _ChewieListItemState();
}
class _ChewieListItemState extends State<ChewieListItem> {
ChewieController _chewieController;
#override
void initState() {
super.initState();
print("ChewieListItem 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: const EdgeInsets.all(8.0),
child: Chewie(
controller: _chewieController,
),
);
}
#override
void dispose() {
print("ChewieListItem dispose");
super.dispose();
// IMPORTANT to dispose of all the used resources
widget.videoPlayerController.dispose();
_chewieController.dispose();
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String videoname = "Video/Intro.mp4";
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
child:
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
ChewieListItem(
key: UniqueKey(),
videoPlayerController: VideoPlayerController.asset(videoname),
looping: false,
),
Container(
margin: EdgeInsets.symmetric(vertical: 20.0),
height: 100.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
IconButton(
icon: Icon(Icons.people),
onPressed: () {
setState(() {
videoname = "Video/Intro.mp4";
print("$videoname");
});
},
),
IconButton(
icon: Icon(Icons.personal_video),
onPressed: () {
setState(() {
videoname = "Video/Intro1.mp4";
print("$videoname");
});
},
),
],
),
),
])),
);
}
}

setState should work for you
onPressed: () {
setState(() {
videoname="Video/Intro1.mp4";
print("$videoname");
});
},

Related

Flutter audioplayers returns wrong playing time?

I'm using audioplayers: 1.1.0 plugin to play audio from url. It's playing well. But the player.onPositionChanged after particular seconds it restarts and timer starts from 0.
So that my slider again starts from 0.
player.onPositionChanged.listen((newPosition) {
prints(newPosition);
});
Output:
0:00:00.000000
0:00:00.002000
0:00:00.203000
0:00:00.405000
0:00:00.607000
0:00:00.810000
0:00:01.013000
0:00:01.215000
0:00:02.027000
0:00:02.232000
0:00:03.863000
0:00:04.882000
0:00:00.236000 // after some seconds again returns from 0
0:00:00.438000
0:00:00.641000
0:00:01.052000
0:00:01.662000
0:00:01.864000
As this function returns again from 0, Slider also restarting as below
This is the entire code
audioplayers: 1.1.0
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'dart:async';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Audio Player'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final player = AudioPlayer();
bool isPlaying = false;
Duration duration = Duration.zero;
Duration position = Duration.zero;
String formatTime(int seconds) {
return '${(Duration(seconds: seconds))}'.split('.')[0].padLeft(8, '0');
}
#override
void initState() {
super.initState();
player.onPlayerStateChanged.listen((state) {
setState(() {
isPlaying = state == PlayerState.playing;
});
});
player.onDurationChanged.listen((newDuration) {
setState(() {
duration = newDuration;
});
});
player.onPositionChanged.listen((newPosition) {
setState(() {
position = newPosition;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Slider(
min: 0,
max: duration.inSeconds.toDouble(),
value: position.inSeconds.toDouble(),
onChanged: (value) {
final position = Duration(seconds: value.toInt());
player.seek(position);
player.resume();
},
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
radius: 25,
child: IconButton(
icon: Icon(
isPlaying ? Icons.pause : Icons.play_arrow,
),
onPressed: () {
if (isPlaying) {
player.pause();
} else {
player.play("https://www.kozco.com/tech/LRMonoPhase4.mp3");
}
},
),
),
SizedBox(
width: 20,
),
CircleAvatar(
radius: 25,
child: IconButton(
icon: const Icon(Icons.stop),
onPressed: () {
player.stop();
},
),
),
],
),
Container(
padding: const EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(formatTime(position.inSeconds)),
Text(formatTime((duration - position).inSeconds)),
],
),
),
],
),
),
);
}
}

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

SnackBar invoked three times in the third screen on single Increment or Decrement, where I'm missing?

I have implemented BlocConsumer for listening to the stream, which will trigger the snack bar widget depending on the state event.
The snack bar is getting triggered three times on a single increment event on the third screen and two times on the second screen. How to make it show once every click on both screens I am using the bloc, flutter_bloc package, any suggestion or direction will be helpful, thank you.
class SecondScreen extends StatefulWidget {
const SecondScreen({Key? key, required this.title, required this.color})
: super(key: key);
final String title;
final Color color;
#override
_SecondScreenState createState() => _SecondScreenState();
}
class _SecondScreenState extends State<SecondScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.title.toString(),
),
backgroundColor: widget.color,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text('SECOND PAGE', style: Theme.of(context).textTheme.headline4),
const SizedBox(height: 40.0),
const Text(
'You have clicked this many times',
),
const SizedBox(height: 10.00),
BlocConsumer<CounterCubit, CounterState>(
listener: (context, state) {
// show a snackbar everytime the state changes
// this block of code is listening to every event triggering in the state
if (state.wasIncremented == true) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Incremented'),
duration: Duration(milliseconds: 100),
),
);
} else if (state.wasIncremented == false) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Decremented'),
duration: Duration(milliseconds: 100),
),
);
}
},
builder: (context, state) {
return Text(
state.counterValue.toString(),
style: Theme.of(context).textTheme.headline4,
);
},
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FloatingActionButton(
onPressed: () {
// TO DO
BlocProvider.of<CounterCubit>(context).decrement();
},
child: const Icon(Icons.remove),
heroTag: const Text('btn1'),
),
FloatingActionButton(
onPressed: () {
// TO DO
BlocProvider.of<CounterCubit>(context).increment();
},
child: const Icon(Icons.add),
heroTag: const Text('btn2')),
],
),
const SizedBox(height: 50.00),
MaterialButton(
height: 50.00,
minWidth: 200.00,
child: const Text('Navigate to Next Screen'),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => BlocProvider<CounterCubit>.value(
value: BlocProvider.of<CounterCubit>(context),
child: const ThirdScreen(
title: 'Third Screen', color: Colors.amberAccent),
),
),
);
},
),
],
),
),
);
}
}
`Cubit state`
// ignore_for_file: unnecessary_this
part of 'counter_cubit.dart';
// #immutable
// abstract class CounterState {}
class CounterState {
int counterValue;
bool wasIncremented;
CounterState({
required this.counterValue,
required this.wasIncremented,
});
// #override
// List<Object> get props => [this.counterValue, this.wasIncremented];
}
`Cubit`
import 'package:bloc/bloc.dart';
part 'counter_state.dart';
class CounterCubit extends Cubit<CounterState> {
CounterCubit() : super(CounterState(counterValue: 0, wasIncremented: false));
void increment() => emit(
CounterState(counterValue: state.counterValue + 1, wasIncremented: true));
void decrement() => emit(CounterState(
counterValue: state.counterValue - 1, wasIncremented: false));
}
`Bloc is provided here`
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return BlocProvider<CounterCubit>(
create: (BuildContext context) => CounterCubit(),
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomeScreen(title: 'First Screen', color: Colors.blueAccent),
),
);
}
}

automatically scroll singleChildScrollView in Flutter Web

I am trying to make a navigation that scrolls automatically when the mouse cursor moves up or down on it.
When I move the cursor up on the navigation section or the SingleChildScrollView, it should go up and similarly when I move the cursor down, it should go down if you guys get what I mean. Sorry my English isn't very good and I am not particularly good at explaining stuff.
Hope you guys can help me out here.
This is my main.dart file:
import 'package:flutter/material.dart';
import 'package:my_portfolio/pages/homepage.dart';
void main() => runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
));
This is my homepage.dart file
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:my_portfolio/widgets/nav_llink.dart';
class HomePage extends StatefulWidget {
const HomePage({Key key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFF2C2A2A),
body: Container(
padding: EdgeInsets.only(left: 120.0, right: 120.0),
child: Row(
children: [
Spacer(),
SingleChildScrollView(
child: Column(
children: [
NavLink(
title: "ABOUT",
onTap: () {},
),
NavLink(
title: "-",
onTap: () {},
),
NavLink(
title: "PROJECTS",
onTap: () {},
),
NavLink(
title: "-",
onTap: () {},
),
NavLink(
title: "CONTACT",
onTap: () {},
),
],
),
),
],
),
),
);
}
}
and finally this are the link "button"
import 'package:flutter/material.dart';
import 'package:flutter/src/gestures/events.dart';
class NavLink extends StatefulWidget {
final String title;
final Function onTap;
Color color = Color(0xFF707070);
int position;
NavLink({ #required this.title, #required this.onTap });
#override
_NavLinkState createState() => _NavLinkState();
}
class _NavLinkState extends State<NavLink> {
#override
Widget build(BuildContext context) {
return RotatedBox(
quarterTurns: 1,
child: Padding(
padding: EdgeInsets.only(right: 80.0, left: 80.0),
child: GestureDetector(
onTap: widget.onTap,
child: MouseRegion(
onHover: updateColor,
onExit: resetColor,
child: Text(
widget.title,
style: TextStyle(
color: widget.color,
fontSize: 180.0,
fontWeight: FontWeight.bold,
),
),
),
),
),
);
}
void updateColor(PointerHoverEvent event) {
setState(() {
widget.color = Colors.white;
widget.position = event.position.dx as int;
});
}
void resetColor(PointerExitEvent event) {
setState(() {
widget.color = Color(0xFF707070);
});
}
}

call method in container flutter

I have class called A.dart in that I am usnign Interprogressbar as below
new Container(
margin: const EdgeInsets.fromLTRB(0, 10, 0, 0),
child: IntervalProgressBar(
direction: IntervalProgressDirection.horizontal,
max: count,
progress: count1,
intervalSize: 2,
size: Size(600, 10),
highlightColor: Colors.pink,
defaultColor: Colors.grey,
intervalColor: Colors.transparent,
intervalHighlightColor: Colors.transparent,
reverse: false,
radius: 0)),
Once the user clicks a button I am navigating to another class from A.dart to a class called B.dart. Once use completes process in class B.dart I ll pop the class B.dart. Again A.dart will be visible for the user. So my question us how can I restart the IntervalProgressBar with the updated value once user comes from B.dart to A,dart.
You can copy paste run full code below
You can await Navigator.push then call setState
void _gotoB() async {
String parameter = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => RouteB()),
);
setState(() {
count1 = int.tryParse(parameter);
});
}
...
RaisedButton(
child: Text('Go back'),
onPressed: () {
Navigator.pop(context, _textEditingController.text);
},
),
working demo
full code
import 'package:flutter/material.dart';
import 'package:intervalprogressbar/intervalprogressbar.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int count = 10;
int count1 = 3;
void _gotoB() async {
String parameter = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => RouteB()),
);
setState(() {
count1 = int.tryParse(parameter);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
margin: const EdgeInsets.fromLTRB(0, 10, 0, 0),
child: IntervalProgressBar(
direction: IntervalProgressDirection.horizontal,
max: count,
progress: count1,
intervalSize: 2,
size: Size(600, 10),
highlightColor: Colors.pink,
defaultColor: Colors.grey,
intervalColor: Colors.transparent,
intervalHighlightColor: Colors.transparent,
reverse: false,
radius: 0)),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _gotoB,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class RouteB extends StatefulWidget {
#override
_RouteBState createState() => _RouteBState();
}
class _RouteBState extends State<RouteB> {
TextEditingController _textEditingController = TextEditingController();
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(
children: [
TextField(
controller: _textEditingController,
),
RaisedButton(
child: Text('Go back'),
onPressed: () {
Navigator.pop(context, _textEditingController.text);
},
),
],
)),
);
}
}