Why player.pause() doesn't work from State of AudioPlayerWidget?

33 views Asked by At

I would like to simply stop the audio, played by an AudioPlayer Widget, created in this class:

import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';

class AudioPlayerWidget extends StatefulWidget {
  AudioPlayer player = AudioPlayer();

  Future<void> playSong(String path) async {
    await player.setAsset(path);
    await player.play();
  }

  AudioPlayerWidget({super.key});
  State<AudioPlayerWidget> createState() => _AudioPlayerWidgetState();
}

class _AudioPlayerWidgetState extends State<AudioPlayerWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: IconButton(
        color: const Color(0xffE3E5E8),
        icon: const Icon(Icons.pause),
        iconSize: 40.0,
        onPressed: () {
          setState(() 
            {widget.player.pause();
          });
        },
      ),
    );
  }
}

So far, the audio start to play, but after pressing the IconButton, it doesn't stop. What do I wrong? Thank you for help!

1

There are 1 answers

0
rpereira On

The player is part of the state of the Widget, it shouldn't be initialized with the widget itself, but in it's state.

Try moving the player to '_AudioPlayerWidgetState':

class AudioPlayerWidget extends StatefulWidget {

  const AudioPlayerWidget({super.key});

  @override
  State<AudioPlayerWidget> createState() => _AudioPlayerWidgetState();
}

class _AudioPlayerWidgetState extends State<AudioPlayerWidget> {
  AudioPlayer player = AudioPlayer();

  @override
  void initState() {
    playSong('audio/sample.mp3');
    super.initState();

  }
  Future<void> playSong(String path) async {
    await player.setAsset(path);
    await player.play();
  }


  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        IconButton(
          color: const Color(0xffE3E5E8),
          icon: const Icon(Icons.pause),
          iconSize: 40.0,
          onPressed: () {
            player.pause();
          },
        ),
      ],
    );
  }
}