1
+ import 'dart:async' ;
2
+
1
3
import 'package:audioplayers/audioplayers.dart' ;
2
4
import 'package:flutter/material.dart' ;
3
5
import 'package:inside_chassidus/data/insideData.dart' ;
4
6
import 'package:provider/provider.dart' ;
5
7
6
8
class PlayButton extends StatefulWidget {
7
9
final Media media;
10
+ final AudioPlayer audioPlayer;
8
11
9
- PlayButton ({@required this .media});
12
+ PlayButton ({@required this .media, @required this .audioPlayer });
10
13
11
14
@override
12
15
State <StatefulWidget > createState () => _PlayButtonState ();
13
16
}
14
17
15
18
class _PlayButtonState extends State <PlayButton > {
16
- bool isPlaying = false ;
19
+ bool isPlaying;
20
+ StreamSubscription <AudioPlayerState > subscription;
21
+
22
+ @override void initState () {
23
+ super .initState ();
24
+
25
+ subscription = widget.audioPlayer.onPlayerStateChanged.listen (_listenToStateChange);
26
+ }
27
+
28
+ @override void dispose () {
29
+ subscription? .cancel ();
30
+
31
+ super .dispose ();
32
+ }
17
33
18
34
@override
19
- Widget build (BuildContext context) => GestureDetector (
20
- onTap: () {
21
- this .setState (() => this .isPlaying = ! this .isPlaying);
22
-
23
- var player = Provider .of <AudioPlayer >(context);
24
-
25
- if (this .isPlaying) {
26
- player.play (this .widget.media.source);
27
- } else {
28
- player.pause ();
29
- }
30
- },
31
- child: Icon (this .isPlaying ? Icons .pause : Icons .play_arrow));
32
- }
35
+ Widget build (BuildContext context) {
36
+ isPlaying = widget.audioPlayer.state == AudioPlayerState .PLAYING ;
37
+
38
+ return GestureDetector (
39
+ onTap: () {
40
+ this .setState (() => this .isPlaying = ! this .isPlaying);
41
+
42
+ var player = Provider .of <AudioPlayer >(context);
43
+
44
+ if (this .isPlaying) {
45
+ player.play (this .widget.media.source);
46
+ } else {
47
+ player.pause ();
48
+ }
49
+ },
50
+ child: Icon (this .isPlaying ? Icons .pause : Icons .play_arrow));
51
+ }
52
+
53
+ _listenToStateChange (AudioPlayerState state) {
54
+ bool isPlaying = state == AudioPlayerState .PLAYING ;
55
+
56
+ if (isPlaying != this .isPlaying) {
57
+ this .setState (() => this .isPlaying = isPlaying);
58
+ }
59
+ }
60
+ }
0 commit comments