[flutter] Flutter Riverpod에서 음악 재생기 앱 만들기

Flutter Riverpod은 Flutter 애플리케이션의 상태 관리 솔루션으로서 강력한 기능과 쉬운 사용법을 제공합니다. 이 기술을 활용하여 음악 재생기 앱을 만들어보겠습니다.

목차

의존성 추가

먼저, flutter_riverpod 패키지를 프로젝트에 추가해야 합니다. pubspec.yaml 파일에 다음과 같이 패키지를 추가합니다:

dependencies:
  flutter:
    sdk: flutter
  flutter_riverpod: ^1.0.3
  audioplayers: ^0.20.1

이제 패키지 매니저를 사용하여 의존성을 업데이트합니다:

flutter pub get

음악 데이터 모델 생성

앱에서 사용할 음악 데이터 모델을 생성합니다. Music 클래스를 만들어 음악의 제목, 아티스트, 앨범 등을 표현할 수 있습니다.

class Music {
  final String title;
  final String artist;
  final String album;
  final String url;

  Music({
    required this.title,
    required this.artist,
    required this.album,
    required this.url,
  });
}

Riverpod Provider 생성

다음으로, Riverpod Provider를 사용하여 음악 재생 상태를 관리합니다. StateNotifier를 이용하여 음악 재생 및 일시정지 상태를 다룰 수 있습니다.

import 'package:flutter_riverpod/flutter_riverpod.dart';

final musicProvider = StateNotifierProvider<MusicPlayerNotifier, bool>((ref) {
  return MusicPlayerNotifier();
});

class MusicPlayerNotifier extends StateNotifier<bool> {
  MusicPlayerNotifier() : super(false);

  void togglePlayPause() {
    state = !state;
  }
}

UI 작성

마지막으로, UI를 작성합니다. 음악 재생 버튼에 Riverpod Provider를 연결하여 상태를 관리하고, 필요에 따라 음악 데이터를 표시할 수 있습니다.

Consumer(builder: (context, watch, child) {
  final isPlaying = watch(musicProvider);
  return ElevatedButton(
    onPressed: () {
      context.read(musicProvider.notifier).togglePlayPause();
    },
    child: isPlaying ? Icon(Icons.pause) : Icon(Icons.play_arrow),
  );
})

이제 여러분은 Flutter Riverpod을 사용하여 음악 재생기 애플리케이션을 만들 수 있습니다.Flutter Riverpod에서 음악 재생기 앱 만들기

참고 자료

Happy coding! 🎵