From e49408e5b0a185555c4efe8a6c7c4974ad33c81b Mon Sep 17 00:00:00 2001 From: Christian Pauly Date: Tue, 14 Feb 2023 12:54:57 +0100 Subject: [PATCH] refactor: Do only instantiate AudioPlayer() object when in use --- lib/pages/chat/events/audio_player.dart | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/pages/chat/events/audio_player.dart b/lib/pages/chat/events/audio_player.dart index f52727a1..e92ece3a 100644 --- a/lib/pages/chat/events/audio_player.dart +++ b/lib/pages/chat/events/audio_player.dart @@ -29,7 +29,7 @@ enum AudioPlayerStatus { notDownloaded, downloading, downloaded } class AudioPlayerState extends State { AudioPlayerStatus status = AudioPlayerStatus.notDownloaded; - final AudioPlayer audioPlayer = AudioPlayer(); + AudioPlayer? audioPlayer; StreamSubscription? onAudioPositionChanged; StreamSubscription? onDurationChanged; @@ -44,8 +44,8 @@ class AudioPlayerState extends State { @override void dispose() { - if (audioPlayer.playerState.playing) { - audioPlayer.stop(); + if (audioPlayer?.playerState.playing == true) { + audioPlayer?.stop(); } onAudioPositionChanged?.cancel(); onDurationChanged?.cancel(); @@ -76,6 +76,7 @@ class AudioPlayerState extends State { } void _playAction() async { + final audioPlayer = this.audioPlayer ??= AudioPlayer(); if (AudioPlayerWidget.currentId != widget.event.eventId) { if (AudioPlayerWidget.currentId != null) { if (audioPlayer.playerState.playing) { @@ -180,7 +181,7 @@ class AudioPlayerState extends State { color: widget.color.withAlpha(64), borderRadius: BorderRadius.circular(64), child: Icon( - audioPlayer.playerState.playing + audioPlayer?.playerState.playing == true ? Icons.pause_outlined : Icons.play_arrow_outlined, color: widget.color, @@ -203,7 +204,7 @@ class AudioPlayerState extends State { for (var i = 0; i < AudioPlayerWidget.wavesCount; i++) Expanded( child: InkWell( - onTap: () => audioPlayer.seek(Duration( + onTap: () => audioPlayer?.seek(Duration( milliseconds: (maxPosition / AudioPlayerWidget.wavesCount) .round() *