Reputation: 331
I'am working on a music player app 📻 in flutter. I'm using audioplayers plugin to get all mp3 files and to play music. I created a separate AudioFunctions class to do all these processes as shown below.
class AudioFunctions{
FlutterAudioQuery audioQuery;
AudioPlayer audioPlayer;
List<SongInfo> songs;
AudioFunctions(){
this.audioQuery = FlutterAudioQuery();
this.audioPlayer = AudioPlayer();
this.songs = [];
}
getLocalSongs() async => this.songs = await audioQuery.getSongs();
String optimiseSongTitles(int index){
String songTitle = '';
if (this.songs[index].displayName.contains('-')){
songTitle = this.songs[index].displayName.split('-')[0];
}
else if(this.songs[index].displayName.contains('_')){
songTitle = this.songs[index].displayName.split('_')[0];
}
return songTitle;
}
void playLocalSong(String path){
audioPlayer.play(path,isLocal: true,);
}
void pauseLocalSong(){
audioPlayer.pause();
}
Stream<Duration> getLength() {
return audioPlayer.onDurationChanged;
}
Stream<Duration> getPosition() {
return audioPlayer.onAudioPositionChanged;
}
Future<int> changeSlider(Duration d){
return audioPlayer.seek(d);
}
}
Now I can access this class to retrieve relevant data🥳 .
Running getLocalSongs
saves a list of all local songs to the songs
variable in the class. However I have to run this each time I create object of AudioFunctions. So, on each screen.😞
Should I use a singleton or provider? Since I'am new to flutter, I don't know how to work with either of them and I have doubts whether if I can use objects in provider.🤔
Show some love💌 and help out a noob👶
Upvotes: 1
Views: 5986
Reputation: 1227
I think a singleton is a good choice here because you probably don't want to call AudioPlayer() on every page again.
class AudioFunctions {
static AudioFunctions _instance = AudioFunctions._();
FlutterAudioQuery audioQuery;
AudioPlayer audioPlayer;
List<SongInfo> songs;
static AudioFunctions get instance => _instance;
AudioFunctions._() {
this.audioQuery = FlutterAudioQuery();
this.audioPlayer = AudioPlayer();
this.songs = [];
}
getLocalSongs() async => this.songs = await audioQuery.getSongs();
}
To access AudioFunctions now you can call AudioFunctions.instance
.
I have changed your constructor to AudioFunctions._()
so that it can no longer be called outside the file.
Upvotes: 4