fix(player): 改用墙钟驱动飘心动画

This commit is contained in:
Zhou Weidong committed 2026-10-26 19:07:56 +08:00
1 parent c0f65042e6
commit 978c309cd7
6 files changed
+235 -100

No files matched your search

@@ -1,5 +1,7 @@
// Author: fruit.com.cn // Author: fruit.com.cn
import 'dart:async';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -41,53 +43,84 @@ class PlayerDoubleTapHeartBurst extends StatefulWidget {
required this.burstId, required this.burstId,
required this.onCompleted, required this.onCompleted,
this.origin = Offset.zero, this.origin = Offset.zero,
this.now,
}); });
final int burstId; final int burstId;
final VoidCallback onCompleted; final VoidCallback onCompleted;
final Offset origin; final Offset origin;
final DateTime Function()? now;
@override @override
State<PlayerDoubleTapHeartBurst> createState() => State<PlayerDoubleTapHeartBurst> createState() =>
_PlayerDoubleTapHeartBurstState(); _PlayerDoubleTapHeartBurstState();
} }
class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst> class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst> {
with SingleTickerProviderStateMixin { Timer? _timer;
late final AnimationController _controller; late final DateTime _startAt;
late final int _totalMs;
final Stopwatch _lifetime = Stopwatch(); final Stopwatch _lifetime = Stopwatch();
int _elapsedMs = 0;
int _tickCount = 0;
bool _completed = false; bool _completed = false;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_lifetime.start(); _lifetime.start();
final total = _hearts _startAt = _now();
_totalMs = _hearts
.map((heart) => heart.delay + _heartDurationMs) .map((heart) => heart.delay + _heartDurationMs)
.reduce((left, right) => left > right ? left : right); .reduce((left, right) => left > right ? left : right);
if (kDebugMode) { if (kDebugMode) {
debugPrint( debugPrint(
'[player] phase=heart-burst-start ' '[player] phase=heart-burst-start '
'id=${widget.burstId} count=${_hearts.length} ' 'id=${widget.burstId} count=${_hearts.length} '
'configuredMs=$total at=${widget.origin.dx.toStringAsFixed(1)},' 'configuredMs=$_totalMs at=${widget.origin.dx.toStringAsFixed(1)},'
'${widget.origin.dy.toStringAsFixed(1)}', '${widget.origin.dy.toStringAsFixed(1)}',
); );
} }
_controller = AnimationController( _timer = Timer.periodic(
vsync: this, const Duration(milliseconds: 16),
duration: Duration(milliseconds: total), (_) => _handleTick(),
)..addStatusListener(_onStatus); );
_controller.forward();
} }
void _onStatus(AnimationStatus status) { DateTime _now() => widget.now?.call() ?? DateTime.now();
if (status != AnimationStatus.completed || _completed) return;
void _handleTick() {
if (!mounted || _completed) return;
final rawElapsedMs = _now().difference(_startAt).inMilliseconds;
final elapsedMs = rawElapsedMs < 0
? 0
: rawElapsedMs > _totalMs
? _totalMs
: rawElapsedMs;
_elapsedMs = elapsedMs;
_tickCount++;
if (kDebugMode && _tickCount % 10 == 0) {
debugPrint(
'[player] phase=heart-tick id=${widget.burstId} '
'elapsedMs=$_elapsedMs',
);
}
if (_elapsedMs >= _totalMs) {
_complete();
return;
}
setState(() {});
}
void _complete() {
if (_completed) return;
_completed = true; _completed = true;
_timer?.cancel();
if (kDebugMode) { if (kDebugMode) {
debugPrint( debugPrint(
'[player] phase=heart-burst-complete ' '[player] phase=heart-burst-complete '
'id=${widget.burstId} ' 'id=${widget.burstId} '
'configuredMs=${_controller.duration?.inMilliseconds ?? 0}', 'configuredMs=$_totalMs',
); );
} }
widget.onCompleted(); widget.onCompleted();
@@ -96,9 +129,7 @@ class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
@override @override
void dispose() { void dispose() {
if (kDebugMode) { if (kDebugMode) {
final elapsedMs = _completed final elapsedMs = _completed ? _totalMs : _elapsedMs;
? _controller.duration?.inMilliseconds ?? 0
: _lifetime.elapsedMilliseconds;
debugPrint( debugPrint(
'[player] phase=heart-burst-dispose ' '[player] phase=heart-burst-dispose '
'id=${widget.burstId} elapsedMs=$elapsedMs ' 'id=${widget.burstId} elapsedMs=$elapsedMs '
@@ -114,44 +145,33 @@ class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
} }
} }
_lifetime.stop(); _lifetime.stop();
_controller _timer?.cancel();
..removeStatusListener(_onStatus) _timer = null;
..dispose();
super.dispose(); super.dispose();
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return IgnorePointer( return IgnorePointer(
child: AnimatedBuilder( child: Stack(
animation: _controller, fit: StackFit.expand,
builder: (context, _) { clipBehavior: Clip.none,
final elapsed = children: [
_controller.value * _controller.duration!.inMilliseconds; for (var index = 0; index < _hearts.length; index++)
return Stack( _heart(_hearts[index], _elapsedMs.toDouble(), index),
fit: StackFit.expand, if (kDebugMode)
clipBehavior: Clip.none, Positioned(
children: [ left: widget.origin.dx + 8,
for (var index = 0; index < _hearts.length; index++) top: widget.origin.dy + 10,
_heart(_hearts[index], elapsed, index), child: IgnorePointer(
if (kDebugMode) child: Text(
Positioned( '${_elapsedMs}ms',
left: widget.origin.dx + 8, key: const Key('heart-burst-elapsed-debug'),
top: widget.origin.dy + 10, style: const TextStyle(color: Colors.white60, fontSize: 11),
child: IgnorePointer(
child: Text(
'${elapsed.round()}ms',
key: const Key('heart-burst-elapsed-debug'),
style: const TextStyle(
color: Colors.white60,
fontSize: 11,
),
),
),
), ),
], ),
); ),
}, ],
), ),
); );
} }
@@ -176,6 +176,7 @@ class _PlayerTapGestureRegionState extends State<PlayerTapGestureRegion> {
key: ValueKey('heart-overlay-$id'), key: ValueKey('heart-overlay-$id'),
burstId: id, burstId: id,
origin: origin, origin: origin,
now: widget.now,
onCompleted: removeEntry, onCompleted: removeEntry,
), ),
), ),
+30 -16
View File
@@ -48,7 +48,6 @@ void main() {
), ),
findsOneWidget, findsOneWidget,
); );
await tester.pumpAndSettle();
} }
}); });
@@ -94,7 +93,7 @@ void main() {
await tester.tapAt(center); await tester.tapAt(center);
await tester.pump(); await tester.pump();
expect(repository.likeTargets, hasLength(1)); expect(repository.likeTargets, hasLength(1));
await tester.pump(const Duration(milliseconds: 2300)); await _pumpTestClock(tester, clock, const Duration(milliseconds: 1600));
clock.advance(const Duration(milliseconds: 500)); clock.advance(const Duration(milliseconds: 500));
await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500));
@@ -136,24 +135,19 @@ void main() {
final burstFinder = find.byType(PlayerDoubleTapHeartBurst); final burstFinder = find.byType(PlayerDoubleTapHeartBurst);
final gestureState = tester.state(gestureFinder); final gestureState = tester.state(gestureFinder);
final burstState = tester.state(burstFinder); final burstState = tester.state(burstFinder);
var elapsedMs = 100;
for (var index = 0; index < 30; index++) { for (var index = 0; index < 30; index++) {
key.currentState!.rebuild(); key.currentState!.rebuild();
clock.advance(const Duration(milliseconds: 16));
await tester.pump(const Duration(milliseconds: 16)); await tester.pump(const Duration(milliseconds: 16));
elapsedMs += 16;
} }
expect(tester.state(gestureFinder), same(gestureState)); expect(tester.state(gestureFinder), same(gestureState));
expect(tester.state(burstFinder), same(burstState)); expect(tester.state(burstFinder), same(burstState));
expect(find.byKey(const Key('double-tap-heart-0')), findsOneWidget); expect(find.byKey(const Key('double-tap-heart-0')), findsOneWidget);
while (burstFinder.evaluate().isNotEmpty && elapsedMs < 2000) { await _pumpTestClock(tester, clock, const Duration(milliseconds: 1600));
await tester.pump(const Duration(milliseconds: 16));
elapsedMs += 16;
}
expect(burstFinder, findsNothing); expect(burstFinder, findsNothing);
expect(elapsedMs, greaterThanOrEqualTo(1500));
}); });
testWidgets('heart burst starts at tapped location', (tester) async { testWidgets('heart burst starts at tapped location', (tester) async {
@@ -192,17 +186,21 @@ void main() {
}; };
var elapsedMs = 0; var elapsedMs = 0;
try { try {
final clock = _TestClock();
final key = GlobalKey<_RemovableGestureHarnessState>(); final key = GlobalKey<_RemovableGestureHarnessState>();
await tester.pumpWidget( await tester.pumpWidget(
MaterialApp(home: _RemovableGestureHarness(key: key)), MaterialApp(
home: _RemovableGestureHarness(key: key, clock: clock),
),
); );
const tapPosition = Offset(120, 220); const tapPosition = Offset(120, 220);
await tester.tapAt(tapPosition); await tester.tapAt(tapPosition);
clock.advance(const Duration(milliseconds: 100));
await tester.pump(const Duration(milliseconds: 100)); await tester.pump(const Duration(milliseconds: 100));
await tester.tapAt(tapPosition); await tester.tapAt(tapPosition);
await tester.pump(); await tester.pump();
await tester.pump(const Duration(milliseconds: 100)); await _pumpTestClock(tester, clock, const Duration(milliseconds: 100));
final burstFinder = find.byType(PlayerDoubleTapHeartBurst); final burstFinder = find.byType(PlayerDoubleTapHeartBurst);
expect(burstFinder, findsOneWidget); expect(burstFinder, findsOneWidget);
@@ -212,10 +210,8 @@ void main() {
expect(burstFinder, findsOneWidget); expect(burstFinder, findsOneWidget);
elapsedMs = 100; elapsedMs = 100;
while (burstFinder.evaluate().isNotEmpty && elapsedMs < 2000) { await _pumpTestClock(tester, clock, const Duration(milliseconds: 1600));
await tester.pump(const Duration(milliseconds: 16)); elapsedMs += 1600;
elapsedMs += 16;
}
expect(burstFinder, findsNothing); expect(burstFinder, findsNothing);
} finally { } finally {
debugPrint = originalDebugPrint; debugPrint = originalDebugPrint;
@@ -380,7 +376,9 @@ class _HarnessState extends State<_Harness> {
} }
class _RemovableGestureHarness extends StatefulWidget { class _RemovableGestureHarness extends StatefulWidget {
const _RemovableGestureHarness({super.key}); const _RemovableGestureHarness({super.key, required this.clock});
final _TestClock clock;
@override @override
State<_RemovableGestureHarness> createState() => State<_RemovableGestureHarness> createState() =>
@@ -415,6 +413,7 @@ class _RemovableGestureHarnessState extends State<_RemovableGestureHarness> {
gestureKey: const Key('removable-gesture'), gestureKey: const Key('removable-gesture'),
enabled: true, enabled: true,
doubleTapEnabled: true, doubleTapEnabled: true,
now: widget.clock.now,
onSingleTap: () {}, onSingleTap: () {},
onDoubleTapLike: (_) {}, onDoubleTapLike: (_) {},
onLongPressStart: (_, _) {}, onLongPressStart: (_, _) {},
@@ -437,3 +436,18 @@ class _TestClock {
_now = _now.add(duration); _now = _now.add(duration);
} }
} }
Future<void> _pumpTestClock(
WidgetTester tester,
_TestClock clock,
Duration duration,
) async {
const frameMs = 16;
var remainingMs = duration.inMilliseconds;
while (remainingMs > 0) {
final stepMs = remainingMs >= frameMs ? frameMs : remainingMs;
clock.advance(Duration(milliseconds: stepMs));
await tester.pump(const Duration(milliseconds: frameMs));
remainingMs -= stepMs;
}
}
+54 -16
View File
@@ -8,14 +8,19 @@ void main() {
testWidgets('should_show_three_develop_hearts_when_burst_starts', ( testWidgets('should_show_three_develop_hearts_when_burst_starts', (
tester, tester,
) async { ) async {
final clock = _HeartClock();
await tester.pumpWidget( await tester.pumpWidget(
const MaterialApp( MaterialApp(
home: Scaffold( home: Scaffold(
body: PlayerDoubleTapHeartBurst(burstId: 1, onCompleted: _noop), body: PlayerDoubleTapHeartBurst(
burstId: 1,
now: clock.now,
onCompleted: _noop,
),
), ),
), ),
); );
await tester.pump(const Duration(milliseconds: 200)); await _pumpHeartTime(tester, clock, const Duration(milliseconds: 200));
expect(find.byIcon(Icons.favorite_rounded), findsNWidgets(3)); expect(find.byIcon(Icons.favorite_rounded), findsNWidgets(3));
expect(_size(tester, 0), 48); expect(_size(tester, 0), 48);
@@ -42,18 +47,23 @@ void main() {
testWidgets('heart burst keeps opacity then fades after 55 percent', ( testWidgets('heart burst keeps opacity then fades after 55 percent', (
tester, tester,
) async { ) async {
final clock = _HeartClock();
await tester.pumpWidget( await tester.pumpWidget(
const MaterialApp( MaterialApp(
home: Scaffold( home: Scaffold(
body: PlayerDoubleTapHeartBurst(burstId: 2, onCompleted: _noop), body: PlayerDoubleTapHeartBurst(
burstId: 2,
now: clock.now,
onCompleted: _noop,
),
), ),
), ),
); );
await tester.pump(const Duration(milliseconds: 450)); await _pumpHeartTime(tester, clock, const Duration(milliseconds: 450));
expect(_opacity(tester, 0), closeTo(1, 1e-9)); expect(_opacity(tester, 0), closeTo(1, 1e-9));
await tester.pump(const Duration(milliseconds: 750)); await _pumpHeartTime(tester, clock, const Duration(milliseconds: 750));
expect(_opacity(tester, 0), lessThan(0.5)); expect(_opacity(tester, 0), lessThan(0.5));
}); });
@@ -61,8 +71,9 @@ void main() {
tester, tester,
) async { ) async {
const origin = Offset(300, 546); const origin = Offset(300, 546);
final clock = _HeartClock();
await tester.pumpWidget( await tester.pumpWidget(
const MaterialApp( MaterialApp(
home: Scaffold( home: Scaffold(
body: Stack( body: Stack(
fit: StackFit.expand, fit: StackFit.expand,
@@ -71,6 +82,7 @@ void main() {
child: PlayerDoubleTapHeartBurst( child: PlayerDoubleTapHeartBurst(
burstId: 4, burstId: 4,
origin: origin, origin: origin,
now: clock.now,
onCompleted: _noop, onCompleted: _noop,
), ),
), ),
@@ -93,7 +105,7 @@ void main() {
lessThanOrEqualTo(1), lessThanOrEqualTo(1),
); );
await tester.pump(const Duration(milliseconds: 750)); await _pumpHeartTime(tester, clock, const Duration(milliseconds: 750));
final midpoint = tester.getCenter(firstHeart); final midpoint = tester.getCenter(firstHeart);
expect(midpoint.dy, lessThan(origin.dy)); expect(midpoint.dy, lessThan(origin.dy));
expect((midpoint.dx - origin.dx).abs(), lessThanOrEqualTo(1)); expect((midpoint.dx - origin.dx).abs(), lessThanOrEqualTo(1));
@@ -103,26 +115,24 @@ void main() {
tester, tester,
) async { ) async {
var completed = false; var completed = false;
var elapsedMs = 0; final clock = _HeartClock();
await tester.pumpWidget( await tester.pumpWidget(
MaterialApp( MaterialApp(
home: Scaffold( home: Scaffold(
body: PlayerDoubleTapHeartBurst( body: PlayerDoubleTapHeartBurst(
burstId: 3, burstId: 3,
now: clock.now,
onCompleted: () => completed = true, onCompleted: () => completed = true,
), ),
), ),
), ),
); );
while (!completed && elapsedMs < 2000) { await _pumpHeartTime(tester, clock, const Duration(milliseconds: 1600));
await tester.pump(const Duration(milliseconds: 16));
elapsedMs += 16;
}
expect(completed, isTrue); expect(completed, isTrue);
expect(elapsedMs, greaterThanOrEqualTo(1584)); expect(clock.elapsedMs, greaterThanOrEqualTo(1590));
expect(elapsedMs, lessThanOrEqualTo(1616)); expect(clock.elapsedMs, lessThanOrEqualTo(1600));
}); });
} }
@@ -141,3 +151,31 @@ double _opacity(WidgetTester tester, int index) {
} }
void _noop() {} void _noop() {}
Future<void> _pumpHeartTime(
WidgetTester tester,
_HeartClock clock,
Duration duration,
) async {
const frameMs = 16;
var remainingMs = duration.inMilliseconds;
while (remainingMs > 0) {
final stepMs = remainingMs >= frameMs ? frameMs : remainingMs;
clock.advance(Duration(milliseconds: stepMs));
await tester.pump(const Duration(milliseconds: frameMs));
remainingMs -= stepMs;
}
}
class _HeartClock {
DateTime _now = DateTime(2026, 10, 26, 12);
DateTime now() => _now;
int get elapsedMs =>
_now.difference(DateTime(2026, 10, 26, 12)).inMilliseconds;
void advance(Duration duration) {
_now = _now.add(duration);
}
}
+17 -1
View File
@@ -680,6 +680,7 @@ void main() {
} }
await tester.pump(); await tester.pump();
await tester.pump(const Duration(milliseconds: 300)); await tester.pump(const Duration(milliseconds: 300));
await _waitForBufferedHeartFrames(tester);
expect(logic.session.userWantsPlay, isTrue); expect(logic.session.userWantsPlay, isTrue);
expect(find.byKey(const Key('player-play-toggle')), findsNothing); expect(find.byKey(const Key('player-play-toggle')), findsNothing);
@@ -699,7 +700,7 @@ void main() {
AppColors.doubleTapHeartRed, AppColors.doubleTapHeartRed,
); );
await tester.pump(const Duration(milliseconds: 2300)); await _waitForHeartCompletion(tester);
expect(find.byKey(const Key('double-tap-heart-0')), findsNothing); expect(find.byKey(const Key('double-tap-heart-0')), findsNothing);
expect(logic.session.userWantsPlay, isTrue); expect(logic.session.userWantsPlay, isTrue);
}); });
@@ -723,6 +724,7 @@ void main() {
await tester.tapAt(const Offset(80, 300)); await tester.tapAt(const Offset(80, 300));
await tester.pump(); await tester.pump();
await tester.pump(const Duration(milliseconds: 300)); await tester.pump(const Duration(milliseconds: 300));
await _waitForBufferedHeartFrames(tester);
expect(logic.session.userWantsPlay, isTrue); expect(logic.session.userWantsPlay, isTrue);
expect(interactions.likeTargets, hasLength(1)); expect(interactions.likeTargets, hasLength(1));
@@ -1818,6 +1820,20 @@ Future<void> _clearFromMore(WidgetTester tester) async {
await tester.pumpAndSettle(); await tester.pumpAndSettle();
} }
Future<void> _waitForBufferedHeartFrames(WidgetTester tester) async {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 120)),
);
await tester.pump(const Duration(milliseconds: 120));
}
Future<void> _waitForHeartCompletion(WidgetTester tester) async {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 1700)),
);
await tester.pump(const Duration(milliseconds: 16));
}
Future<void> _openSeriesPlayer( Future<void> _openSeriesPlayer(
WidgetTester tester, { WidgetTester tester, {
Key cardKey = const Key('home-feed-card-city-lights-demo'), Key cardKey = const Key('home-feed-card-city-lights-demo'),
+66 -20
View File
@@ -13,21 +13,26 @@ void main() {
var completedCalls = 0; var completedCalls = 0;
const origin = Offset(300, 546); const origin = Offset(300, 546);
final clock = _HeartClock();
await tester.pumpWidget( await tester.pumpWidget(
MaterialApp( MaterialApp(
home: Scaffold( home: TickerMode(
body: Stack( enabled: false,
fit: StackFit.expand, child: Scaffold(
clipBehavior: Clip.none, body: Stack(
children: [ fit: StackFit.expand,
Positioned.fill( clipBehavior: Clip.none,
child: PlayerDoubleTapHeartBurst( children: [
burstId: 91, Positioned.fill(
origin: origin, child: PlayerDoubleTapHeartBurst(
onCompleted: () => completedCalls++, burstId: 91,
origin: origin,
now: clock.now,
onCompleted: () => completedCalls++,
),
), ),
), ],
], ),
), ),
), ),
), ),
@@ -52,15 +57,56 @@ void main() {
lessThanOrEqualTo(1), lessThanOrEqualTo(1),
); );
await tester.pump(const Duration(milliseconds: 400)); await _pumpHeartTime(tester, clock, const Duration(milliseconds: 300));
final midpoint = tester.getCenter(firstHeart); final center300 = tester.getCenter(firstHeart);
debugPrint( debugPrint('[heart-pixels] t=300 center=${center300.dx},${center300.dy}');
'[heart-pixels] after400ms center=${midpoint.dx},${midpoint.dy}', expect(center300.dy, lessThan(initialCenter.dy));
); expect((center300.dx - origin.dx).abs(), lessThanOrEqualTo(30));
expect(midpoint.dy, lessThan(origin.dy - 40));
expect((midpoint.dx - origin.dx).abs(), lessThanOrEqualTo(30));
await tester.pump(const Duration(milliseconds: 1200)); await _pumpHeartTime(tester, clock, const Duration(milliseconds: 300));
final center600 = tester.getCenter(firstHeart);
debugPrint('[heart-pixels] t=600 center=${center600.dx},${center600.dy}');
expect(center600.dy, lessThan(center300.dy));
expect((center600.dx - origin.dx).abs(), lessThanOrEqualTo(30));
await _pumpHeartTime(tester, clock, const Duration(milliseconds: 300));
final center900 = tester.getCenter(firstHeart);
debugPrint('[heart-pixels] t=900 center=${center900.dx},${center900.dy}');
expect(center900.dy, lessThan(center600.dy));
expect((center900.dx - origin.dx).abs(), lessThanOrEqualTo(30));
expect({
initialCenter.dy,
center300.dy,
center600.dy,
center900.dy,
}, hasLength(4));
await _pumpHeartTime(tester, clock, const Duration(milliseconds: 700));
expect(completedCalls, 1); expect(completedCalls, 1);
}); });
} }
Future<void> _pumpHeartTime(
WidgetTester tester,
_HeartClock clock,
Duration duration,
) async {
const frameMs = 16;
var remainingMs = duration.inMilliseconds;
while (remainingMs > 0) {
final stepMs = remainingMs >= frameMs ? frameMs : remainingMs;
clock.advance(Duration(milliseconds: stepMs));
await tester.pump(const Duration(milliseconds: frameMs));
remainingMs -= stepMs;
}
}
class _HeartClock {
DateTime _now = DateTime(2026, 10, 26, 12);
DateTime now() => _now;
void advance(Duration duration) {
_now = _now.add(duration);
}
}