Skip to content

Commit

Permalink
refactor: use timer instead of future<void> (#374)
Browse files Browse the repository at this point in the history
* change future to Timer

* Update pressable_widget.dart
  • Loading branch information
tilucasoli authored Jul 11, 2024
1 parent 2e88dc9 commit e09255f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 6 deletions.
29 changes: 23 additions & 6 deletions packages/mix/lib/src/widgets/widget_state/pressable_widget.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:async';

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

Expand Down Expand Up @@ -277,15 +279,30 @@ abstract class _MixStateWidgetBuilderState<T extends _MixStateWidgetBuilder>
setState(fn);
}

Future<void> unpressAfterDelay(int initialPressCount) async {
final delay = widget.unpressDelay;
Timer? _timer;

if (delay != Duration.zero) {
await Future.delayed(delay);
@override
void dispose() {
_timer?.cancel();
super.dispose();
}

void unpressAfterDelay(int initialPressCount) {
void unpressCallback() {
if (_isPressed && _pressCount == initialPressCount) {
updateState(() => _isPressed = false);
}
}

if (_isPressed && _pressCount == initialPressCount) {
updateState(() => _isPressed = false);
_timer?.cancel();
_timer = null;

final delay = widget.unpressDelay;

if (delay != Duration.zero) {
_timer = Timer(delay, unpressCallback);
} else {
unpressCallback();
}
}

Expand Down
25 changes: 25 additions & 0 deletions packages/mix/test/src/widgets/pressable/pressable_widget_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,31 @@ void main() {
});
});

testWidgets('Pressable cancel timer on dispose', (WidgetTester tester) async {
var wasPressed = false;

await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Pressable(
autofocus: true,
unpressDelay: const Duration(minutes: 1),
onPress: () {
wasPressed = !wasPressed;
},
child: const Text('Tap me'),
),
),
),
);

await tester.sendKeyEvent(LogicalKeyboardKey.enter);
expect(wasPressed, isTrue);

await tester.sendKeyEvent(LogicalKeyboardKey.enter);
expect(wasPressed, isFalse);
});

group('PressableBox', () {
testWidgets(
'must be clickable when enable is setted to true',
Expand Down

0 comments on commit e09255f

Please sign in to comment.