Query Smarter, Not Harder

BackerLeader posted Originally published at dev.to 1 min read

If you're building a music app with on_audio_query, it’s tempting to call querySongs() everywhere—home screen, playlists, search, etc. But this means repeated storage scans → slower UI, battery drain, and unnecessary complexity.

The Wrong Way – Querying Every Time

final OnAudioQuery audioQuery = OnAudioQuery();

Future<List<SongModel>> getSongs() async {
  return await audioQuery.querySongs(); // Called in every screen
}

In each screen:

final songs = await getSongs(); // Repeats scan again

The Better Way – Query Once, Share via Provider

  • Fetch once in a service (e.g., MusicPlaybackService):
class MusicPlaybackService extends ChangeNotifier {
  List<SongModel> _allSongs = [];

  Future<void> loadSongs() async {
    final OnAudioQuery query = OnAudioQuery();
    _allSongs = await query.querySongs();
    notifyListeners();
  }

  List<SongModel> get allSongs => _allSongs;
}
  • Provide it globally:
runApp(
  ChangeNotifierProvider(
    create: (_) {
      final service = MusicPlaybackService();
      service.loadSongs(); // Fetch once
      return service;
    },
    child: MyApp(),
  ),
);
  • Reuse anywhere without re-querying:

    final allSongs = context.watch().allSongs;

Benefits

  • No repeated disk access.
  • Faster UI transitions (playlist, search, player use the same list).
  • Centralized state → easier maintenance.
If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Music App Bug: Songs Broke on Switching — Here’s Why

rahul mishra - Aug 3

Code Smarter, Not Harder: Top Clean Coding Habits for Backend Devs

Gift Balogun - Apr 26

Why I Started Creating Models in My Flutter Project

rahul mishra - Aug 20

How I Paid Off a Little Technical Debt in My Flutter Music App

rahul mishra - Aug 15

Why does my Flutter music player jump from 0:00 to actual time? (One-liner fix inside!)

rahul mishra - Aug 8
chevron_left