Query Smarter, Not Harder
rahul mishra

rahul mishra @yogi_rahul

About: I love building and currently exploring to build a space for people to feel calm, positive and mentally healthy while getting rewarded.

Location:
Delhi, India
Joined:
Jul 18, 2025

Query Smarter, Not Harder

Publish Date: Jul 26
2 0

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
}
Enter fullscreen mode Exit fullscreen mode

In each screen:

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

The Better Way – Query Once, Share via Provider

  1. 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;
}
Enter fullscreen mode Exit fullscreen mode
  1. Provide it globally:
runApp(
  ChangeNotifierProvider(
    create: (_) {
      final service = MusicPlaybackService();
      service.loadSongs(); // Fetch once
      return service;
    },
    child: MyApp(),
  ),
);
Enter fullscreen mode Exit fullscreen mode
  1. Reuse anywhere without re-querying:

final allSongs = context.watch<MusicPlaybackService>().allSongs;

Benefits

  • No repeated disk access.
  • Faster UI transitions (playlist, search, player use the same list).
  • Centralized state → easier maintenance.

Comments 0 total

    Add comment