Blame view

lib/common/widgets/speaker_widget.dart 2.11 KB
56b412f5   吴启风   feat:扬声器播放动画组件封装
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
  import 'package:flutter/material.dart';
  import 'dart:async';
  
  import 'package:wow_english/common/extension/string_extension.dart';
  
  /// 扬声器播放组件,帧动画
  class SpeakerWidget extends StatefulWidget {
    final bool isPlaying;
    final bool isClickable;
    final double width;
    final double height;
    final VoidCallback? onTap;
  
    SpeakerWidget({
      super.key,
      this.isPlaying = false,
      this.isClickable = true,
      required this.width,
      required this.height,
      this.onTap,
    });
  
    @override
    _SpeakerWidgetState createState() => _SpeakerWidgetState();
  }
  
  class _SpeakerWidgetState extends State<SpeakerWidget>
      with SingleTickerProviderStateMixin {
    late AnimationController _controller;
    int _currentFrame = 0;
    Timer? _timer;
    final List<String> _speakerImagePaths = [
      'ic_speaker_play2'.assetPng,
      'ic_speaker_play0'.assetPng,
      'ic_speaker_play1'.assetPng,
    ];
  
    @override
    void initState() {
      super.initState();
      _controller = AnimationController(
        duration: const Duration(milliseconds: 300), // 每帧的持续时间
        vsync: this,
      );
  
      if (widget.isPlaying) {
        _startAnimation();
      }
    }
  
    @override
    void didUpdateWidget(SpeakerWidget oldWidget) {
      super.didUpdateWidget(oldWidget);
      if (widget.isPlaying != oldWidget.isPlaying) {
        if (widget.isPlaying) {
          _startAnimation();
        } else {
          _stopAnimation();
        }
      }
    }
  
    void _startAnimation() {
      _timer = Timer.periodic(const Duration(milliseconds: 300), (Timer timer) {
        setState(() {
          _currentFrame = ((_currentFrame + 1) % 3);
        });
      });
    }
  
    void _stopAnimation() {
      _timer?.cancel();
      setState(() {
        _currentFrame = 0;
      });
    }
  
    @override
    void dispose() {
      _controller.dispose();
      _timer?.cancel();
      super.dispose();
    }
  
    @override
    Widget build(BuildContext context) {
      return GestureDetector(
        onTap: widget.isClickable ? widget.onTap : null,
        child: Image.asset(
          _speakerImagePaths[_currentFrame],
          width: widget.width,
          height: widget.height,
          fit: BoxFit.cover,
        ),
      );
    }
  }