Show menu

main.dart

  void main() => runApp(DemoApp());

  class DemoApp extends StatelessWidget {
    const DemoApp();

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text("Listen to music"),
          ),
          body: const Center(
            child: MusicWidget(),
          )
        ),
      );
    }
  }
  

music_widget.dart

  class MusicWidget extends StatelessWidget {
    static final _assetsAudioPlayer = AssetsAudioPlayer();

    const MusicWidget();

    @override
    Widget build(BuildContext context) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              IconButton(
                icon: const Icon(Icons.open_in_browser),
                onPressed: () {
                  _assetsAudioPlayer.open(Audio("assets/music.mp3"));
                },
              ),

              StreamBuilder<Duration>(
                stream: _assetsAudioPlayer.currentPosition,
                builder: (context, AsyncSnapshot<Duration> asyncSnapshot) {
                  if (asyncSnapshot.hasData) {
                    final time = asyncSnapshot.data;
                    if (time != null) {
                      return Text("${time.inMinutes}m ${time.inSeconds}s");
                    } else {
                      return const Text("No time available");
                    }
                  }

                  return const Text("0m 0s");
                },
              ),

              StreamBuilder(
                stream: _assetsAudioPlayer.isPlaying,
                builder: (context, AsyncSnapshot<bool> isPlaying) {
                  if (isPlaying.data ?? false) {
                    return IconButton(
                      icon: const Icon(Icons.pause),
                      onPressed: _assetsAudioPlayer.pause,
                    );
                  } else {
                    return IconButton(
                      icon: const Icon(Icons.play_arrow),
                      onPressed: _assetsAudioPlayer.play,
                    );
                  }
                },
              )
            ],
          ),

        ],
      );
    }
  }
  

This website and the book are not official Google products. No affiliations are involved. Built with Java 14 and Vert.X

"Flutter and the related logo are trademarks of Google LLC. We are not endorsed by or affiliated with Google LLC"