Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use timer instead of future<void> #374

Merged
merged 2 commits into from
Jul 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
tilucasoli marked this conversation as resolved.
Show resolved Hide resolved
} 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
Loading