How to Create Music Player UI screen with fully functional in flutter

To create a fully functional music player UI in Flutter using GetX, follow these steps: How to Create Music Player UI screen with fully functional in flutter with step by step

1. Set Up Your Flutter Project

Create a new Flutter project if you haven’t already:

flutter create music_player
cd music_player

2. Add Dependencies

Update your pubspec.yaml to include get for state management and audioplayers for audio playback:

dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.5
  audioplayers: ^0.20.1

Run flutter pub get to install the packages.

3. Create the Music Controller

Create a file named music_controller.dart to handle the music playback logic:

import 'package:get/get.dart';
import 'package:audioplayers/audioplayers.dart';

class MusicController extends GetxController {
  final AudioPlayer _audioPlayer = AudioPlayer();
  var isPlaying = false.obs;
  var duration = Duration.zero.obs;
  var position = Duration.zero.obs;

  @override
  void onInit() {
    super.onInit();

    _audioPlayer.onPlayerStateChanged.listen((state) {
      isPlaying.value = state == PlayerState.PLAYING;
    });

    _audioPlayer.onDurationChanged.listen((d) {
      duration.value = d;
    });

    _audioPlayer.onAudioPositionChanged.listen((p) {
      position.value = p;
    });
  }

  void playPause() {
    if (isPlaying.value) {
      _audioPlayer.pause();
    } else {
      _audioPlayer.play('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3');
    }
  }

  void seekTo(Duration pos) {
    _audioPlayer.seek(pos);
  }

  @override
  void onClose() {
    _audioPlayer.dispose();
    super.onClose();
  }
}

4. Create the Music Player UI

Create a file named music_player_screen.dart for the UI:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'music_controller.dart';

class MusicPlayerScreen extends StatelessWidget {
  final MusicController musicController = Get.put(MusicController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Music Player'),
      ),
      body: Obx(() {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Now Playing',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 20),
            Icon(
              musicController.isPlaying.value ? Icons.music_note : Icons.music_off,
              size: 100,
              color: Colors.blue,
            ),
            SizedBox(height: 20),
            Slider(
              value: musicController.position.value.inSeconds.toDouble(),
              min: 0,
              max: musicController.duration.value.inSeconds.toDouble(),
              onChanged: (value) {
                musicController.seekTo(Duration(seconds: value.toInt()));
              },
            ),
            Text(
              '${musicController.position.value.toString().split('.').first} / ${musicController.duration.value.toString().split('.').first}',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => musicController.playPause(),
              child: Text(musicController.isPlaying.value ? 'Pause' : 'Play'),
            ),
          ],
        );
      }),
    );
  }
}

5. Update the Main Entry Point

Ensure your main.dart uses GetMaterialApp:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'music_player_screen.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Music Player',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MusicPlayerScreen(),
    );
  }
}

6. Run Your App

Finally, run your app:

flutter run

Output

Explanation

  1. MusicController:
  • Manages the audio player state, including play/pause, seeking, and tracking position.
  • Uses Rx types from GetX (obs properties) to automatically update the UI.
  1. MusicPlayerScreen:
  • Uses Obx to reactively rebuild the UI when the controller’s state changes.
  • Provides a play/pause button, a slider for seeking, and displays the current position and duration of the track.

This setup keeps your UI reactive and state management clean, leveraging GetX for efficient and effective state handling.

Related Articles

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top