How to automatically ontap in flutter - flutter

Please help i have a video recording app which starts with a tap and a timer is also started with the same tap and after another tap it stops and timer reset . I want to stop and reset timer when the timer reaches 15 second how to do this please help
GestureDetector(
onTap:
() async {
if (isRecoring) {
stop();
XFile videopath =
await _cameraController.stopVideoRecording();
setState(() {
isRecoring = false;
Navigator.push(
context,
MaterialPageRoute(
builder: (builder) => VideoViewPage(
path: videopath.path,
)));
}
);
} else {
startTime();
await _cameraController.startVideoRecording();
setState(() {
isRecoring = true;
// ignore: use_build_context_synchronously
});
}
},`
i tried adding logical or like this ` if (isRecoring || timer == '15') {stop} but didnt work.
create a diffrent function with a if condition for stop even that didnt work

Firstly you need to define a Duration variable and a Timer to track the timer duration:
var videoDuration = const Duration();
Timer? autoStopRecordingTimer;
Then make a function which will stop the video recording:
void stopRecording()async{
stop();
XFile videopath = await _cameraController.stopVideoRecording();
setState(() {
isRecoring = false;
Navigator.push(
context,
MaterialPageRoute(
builder: (builder) => VideoViewPage(
path: videopath.path,
)));
}
);
}
When starting video recording, start the timer as well. Which will stop the recording if it has been 15 or more seconds:
autoStopRecordingTimer = Timer.periodic(const Duration(seconds: 1), (timer) async {
if(videoDuration.inSeconds>=15){
autoStopRecordingTimer?.cancel();
videoDuration = const Duration();
stopRecording();
} else {
videoDuration+=const Duration(seconds: 1);
}
});

Related

delay after setState is triggered

in the code below that is for throwing dice, I want to wait 2 seconds after each dice throwing. I tested sleep(duration) and await Future.delayed(duration); the first one makes a delay before updating the screen which means when I tap the TextButton, it waits for 2 seconds and then changes the screen, but I want it to be changed and then waits for 2 seconds. The second one actually does nothing and there is no delays.
Here is the code:
Duration delay = const Duration(seconds: 2);
You can call delay inside WidgetsBinding, like this:
setState(() {
...
});
WidgetsBinding.instance.addPostFrameCallback((_) async {
await Future.delayed(Duration(seconds: 2));
print("call"); // update the view then print call after 2 second
});
try..
//Move your onPressCode to a function
Future<void> rollDice() async{
await Future.delayed(Duration(milliseconds: 0), () {
/// your onPressCode
});
}
And on your onPress :
onPressed:() async {
await rollDice();
await Future.delayed(Duration(milliseconds: 2000), () {});
print('this print is show after 2 secs');
}
Edit ...
For prevent double tap, you can create a state called canPress with default value = false ...
onPressed:() async {
if (canPress){
setState(() => canPress = false);
await rollDice();
await Future.delayed(Duration(milliseconds: 2000), () {});
print('this print is show after 2 secs');
setState(() => canPress = true);
}
}

Flutter Future.delayed timer dispose when navigating to other page

In my flutter app, I have a function that has delaye for 5 seconds to activate a button. When I navigate to other page, the timer of the delayed is still working even though I use the "pushReplacement" navigator. Can anyone help me find a way to dispose or cancel this timer when I navigate to other page.
here is the code:
Future sendVerificationEmail() async {
try{
final user =FirebaseAuth.instance.currentUser!;
await user.sendEmailVerification();
setState(() => canResendEmail = false);
await Future.delayed(const Duration(seconds: 5)); // this is the line causing the error
setState(() => canResendEmail = true);
}catch (e) {
Utils.showSnackBar(e.toString());
}
}
and here is the navigation button function:
Future<void> SignOut() async {
await FirebaseAuth.instance.signOut();
Navigator.pushReplacement(
context,MaterialPageRoute(builder: (context) => mainPage()),
);
}
Try using a timer instead
Timer timer = Timer(Duration(seconds: 5), () {
//do something here();
});
// You can dispose the timer like this
timer.cancel();

Maximum Duration of picked video using image picker plugin in Flutter

I'm using image picker plugin to pick videos from gallery in my flutter app. I want to set the maximum duration of the picked video to 30 seconds. The below code doesn't work even after setting the max duration. Is there any way to display an error or automatically trim the first 30secs if users pick a bigger video.
pickVideo(ImageSource src) async {
Navigator.pop(context);
final video = await ImagePicker().getVideo(
source: src,
maxDuration: Duration(seconds: 30),
);
I made a work around for this by throwing an error when a video longer than x seconds is selected. It looks as follows:
Future<void> pickVideo() async {
try {
final picker = ImagePicker();
var pickedFile = await picker.pickVideo(source: ImageSource.gallery, maxDuration: Duration(seconds: maxSeconds));
if (pickedFile == null) {
return;
}
VideoPlayerController testLengthController = new VideoPlayerController.file(File(pickedFile.path));//Your file here
await testLengthController.initialize();
if (testLengthController.value.duration.inSeconds > 60) {
pickedFile = null;
throw('we only allow videos that are shorter than 1 minute!');
} else {
setState(() {
videoFile = XFile(pickedFile.path);
_startVideoPlayer();
});
}
testLengthController.dispose();
} catch (e) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Container(
child: Text(e.toString()),
),
);
});
return;
}
}

Alert Dialog running infinitely

Hello I am trying to run following code, I want to run a specific asynchronous code and show alert dialog until it's running. But the code is not being executed after await showAlertDialog(); this line.
void appendAndRunPythonCode() async {
await showAlertDialog();
await runPythonScript(final_code);
_alertDialogUtils.dismissAlertDialog(context);
}
This is how my showAlertDialog() function is implemented:
Future<void> showAlertDialog() async {
if (!_alertDialogUtils.isShowing) {
await _alertDialogUtils.showAlertDialog(context);
}
}
runPythonCode():
Future<void> runPythonScript(String code) async {
if (inputImg == null) {
ToastUtils.showToastMessage(text: ConstUtils.input_image_empty_notice);
return;
}
if (code.isEmpty) {
ToastUtils.showToastMessage(text: ConstUtils.code_empty);
return;
}
List<String> lines = code.split('\n');
String lastLine = lines.elementAt(lines.length - 4);
if (lastLine.split(' ').elementAt(0).compareTo('outputImage') != 0) {
ToastUtils.showToastMessage(text: ConstUtils.cv_error_line2);
return;
}
data.putIfAbsent("code", () => code);
data.putIfAbsent("inputImg", () => inputImg);
_alertDialogUtils.showAlertDialog(context);
final result = await _channel.invokeMethod("runPythonCVScript", data);
// Add Artifical Delay of 3 seconds..
await Future.delayed(
Duration(seconds: 3),
);
_alertDialogUtils.dismissAlertDialog(context);
setState(
() {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
curve: Curves.easeOut,
duration: const Duration(milliseconds: 300),
);
output = result['textOutput'] ??= "";
error = result['error'] ??= "";
outputImg = (result['graphOutput']);
data.clear();
},
);
}
You shouldn't await the showAlertDialog because runPythonScript won't be executed until the dialog is dismissed.
Remove the await.
Like so:
void appendAndRunPythonCode() async {
showAlertDialog();
await runPythonScript(final_code);
_alertDialogUtils.dismissAlertDialog(context);
}

Flutter 'value >= min && value <= max': is not true

I am building a simple music player type app. I am facing an issue when my audio completed the time it's showing
'package:flutter/src/material/slider.dart': Failed assertion: line 166 pos 15: 'value >= min && value <= max': is not true.
My code
Expanded(
child: Slider(
activeColor: Color(0xffe7ad29),
inactiveColor: Color(0xFF707070),
value: model.playerBarValue,
onChanged: (val) {
model.seekFromBar(val);
},
),
),
class PlayerProvider extends ChangeNotifier {
final player = AssetsAudioPlayer();
String link;
Duration playerTimeNow = Duration(seconds: 0);
Duration playerLength;
double playerBarValue = 0.0;
Episode episode;
Item podcastInfo;
String episodeName, episodeThumbnail;
bool isPlaying = false;
PlayerProvider() {
updateState();
}
play() async {
print("Started Playing");
// Stop previous playing
player.stop();
playerTimeNow = Duration(seconds: 0);
isPlaying = false;
// link = updateLinkToHttps(link);
print(link);
final audio = Audio.network(
link,
metas: Metas(
title: podcastInfo.collectionName,
artist: podcastInfo.artistName,
album: podcastInfo.trackName,
image: MetasImage.network(podcastInfo.artworkUrl600),
//can be MetasImage.network
),
);
var duration = await player.open(
audio,
showNotification: true,
notificationSettings: NotificationSettings(
//seekBarEnabled: false,
//stopEnabled: true,
//customStopAction: (player){
// player.stop();
//}
//prevEnabled: false,
customNextAction: (player) {
print("next1");
forward();
}, customPrevAction: (player) {
print("next2");
backword();
}
//customStopIcon: AndroidResDrawable(name: "ic_stop_custom"),
//customPauseIcon: AndroidResDrawable(name:"ic_pause_custom"),
//customPlayIcon: AndroidResDrawable(name:"ic_play_custom"),
),
);
isPlaying = true;
// player.play(); // Usually you don't want to wait for playback to finish.
print("started");
setState();
}
pause() async {
await player.pause();
isPlaying = false;
print("paused");
setState();
}
resume() async {
//TODO: Setup resume
await player.seek(playerTimeNow);
player.play();
isPlaying = true;
}
speed(double val) async {
print(val);
//TODO: Setup resume
await player.setPlaySpeed(val);
isPlaying = true;
}
updateState() {
player.currentPosition.listen((event) {
playerTimeNow = event;
updatePlayerBar();
});
}
updatePlayerBar() {
int totalLengthInMilliSeconds = playerLength.inMilliseconds;
int totalPlayedInMilliSeconds = playerTimeNow.inMilliseconds;
double newPlayerBarValue =
totalPlayedInMilliSeconds / totalLengthInMilliSeconds;
playerBarValue = newPlayerBarValue;
// print(playerBarValue);
// print(playerTimeNow);
// print(playerLength);
// print(playerLength);
// if (playerLength == playerTimeNow) {
// print('Finish');
// player.stop();
// }
notifyListeners();
}
forward() async {
//TODO: Check if at-least 10 seconds are left;
if (playerTimeNow + Duration(seconds: 10) < playerLength)
await player.seek(playerTimeNow + Duration(seconds: 10));
else
await player.seek(playerLength);
print("Forwarded 10 seconds");
}
backword() async {
Duration back = playerTimeNow.inSeconds > 10
? playerTimeNow - Duration(seconds: 10)
: Duration(seconds: 0);
await player.seek(back);
print("Backwarded 10 seconds");
}
seekFromBar(double val) async {
double totalMillis = playerLength.inMilliseconds * val;
int newMillis = totalMillis.toInt();
Duration newSeekLocations = Duration(milliseconds: newMillis);
await player.seek(newSeekLocations);
print("Seek from Bar");
}
setState() {
notifyListeners();
}
}
When time is finished of player then it's showing this error on red screen. I need to know the fix of this? Mean when it's finished time go to 0 or something. The issue is on the slider I think because if I back from the red screen then my slider goes to zero.
check thet the value of model.playerBarValue is neither Nan or null, and set a max value for the slider.
Slider(
value: model.playerBarValue.isNaN==true || model.playerBarValue==null? 0 : model.playerBarValue,
min: 0.0,
max: duration.inSeconds.toDouble() + 1.0,
onChanged: (value) {
. . .
},
)