Issue
im creating a chat app. I want to display my timer (Widget buildPlayer()) when the record button is started and stop when I click stop icon. currently the button is toggling start to stop. but I want to display timer while recording. how can I do this. chatRoom.dart
I have already implemented TimerWidget separately and access it via timercontroller. timer_widget.dart
appreciate your help on this. you can refer my full chatRoom.dart code from above link if you want. please let me know a way to do this.
Expanded(
flex: 1,
child: Container(
height: 49,
width: 49,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: mainGreen,
),
child: IconButton(
onPressed: () async {
await recorder.toggleRecording();
final isRecording = recorder.isRecording;
setState(() {});
if (isRecording) {
timerController.startTimer();
} else {
timerController.stoptTimer();
}
},
icon: Icon(icon, color: Colors.white,)
),
),
),
Widget buildPlayer() {
final text = recorder.isRecording ? 'Now Recording' : 'Press Start';
final animate = recorder.isRecording;
return CircleAvatar(
radius :92,
backgroundColor: Colors.green,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.mic, size: 32),
TimerWidget(controller: timerController),
SizedBox(height: 8),
Text(text),
]
),
);
}
Solution
I have implemented like this,
Stream<int>? timerStream;
StreamSubscription<int>? timerSubscription;
String minutesStr = '00';
String secondsStr = '00';
// At Recording Start:
timerStream = stopWatchStream();
timerSubscription = timerStream!.listen((int newTick) {
setState(() {
minutesStr = ((newTick / 60) % 60).floor().toString().padLeft(2, '0');
secondsStr = (newTick % 60).floor().toString().padLeft(2, '0');
});
});
// At Recording Stop :
timerSubscription!.cancel();
timerStream = null;
setState(() {
minutesStr = '00';
secondsStr = '00';
});
// Display Timer :
Text('$minutesStr:$secondsStr')
// Handle timeStream
Stream<int> stopWatchStream() {
StreamController<int>? streamController;
Timer? timer;
Duration timerInterval = Duration(seconds: 1);
int counter = 0;
void stopTimer() {
if (timer != null) {
timer!.cancel();
timer = null;
counter = 0;
streamController!.close();
}
}
void tick(_) {
counter++;
streamController!.add(counter);
stopTimer();
}
void startTimer() {
timer = Timer.periodic(timerInterval, tick);
}
streamController = StreamController<int>(
onListen: startTimer,
onCancel: stopTimer,
onResume: startTimer,
onPause: stopTimer,
);
return streamController.stream;
}
Answered By - Yashraj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.