Query Smarter, Not Harder

Backer ●9 ●62 ●109
calendar_today • schedule1 min read
— Originally published at dev.to

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.

Want more #devops & #flutterdev deep dives?

Join 6,129+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

1 Comment

1 vote

More Posts

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

yogirahul - Aug 3, 2025

How to Keep a Telemedicine MVP Small Without Creating Bigger Problems Later

kajolshah - Apr 16

10x the Pull Requests, Not 10x the CI Bill: CircleCI's Rob Zuber on Testing for Coding Agents

Tom Smithverified - Nov 23

Why Theme Setup Matters (More Than You Think)

Dilip Kumar - Nov 18, 2025

Building “R U Ready” – My Flutter Dating App Development Journey

Dilip Kumar - Nov 4, 2025
chevron_left
7.2k Points • 180 Badges
India • yogicode.org
35Posts
102Comments
12Connections
AI Engineer focused on building applications & writing practical guides on coding and machine learning.

Commenters (This Week)

9 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!