From 3da3f4b78a55724c4508349ca6b7db90305e0041 Mon Sep 17 00:00:00 2001 From: Saad AMRANI <62079074+x544D@users.noreply.github.com> Date: Sat, 18 Jan 2025 14:44:06 +0100 Subject: [PATCH] fix: prevent focus loop in PaymentElement widget (#2022) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Removed prints. Co-authored-by: RĂ©mon --- .../lib/src/widgets/payment_element.dart | 30 +++++++++++++++---- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/packages/stripe_web/lib/src/widgets/payment_element.dart b/packages/stripe_web/lib/src/widgets/payment_element.dart index 1ef4ea4b..383ef08d 100644 --- a/packages/stripe_web/lib/src/widgets/payment_element.dart +++ b/packages/stripe_web/lib/src/widgets/payment_element.dart @@ -169,15 +169,35 @@ class PaymentElementState extends State { final FocusNode _focusNode = FocusNode(debugLabel: 'CardField'); FocusNode get _effectiveNode => widget.focusNode ?? _focusNode; + bool _isManuallyFocusing = false; // Track manual focus/blur actions + bool _isCurrentlyFocused = false; // Track current focus state + @override Widget build(BuildContext context) { return Focus( focusNode: _effectiveNode, - onFocusChange: (focus) { - /* if (focus) - element?.focus(); - else - element?.blur(); */ + onFocusChange: (focus) { + // Prevent feedback loop from manual focus/blur actions + if (_isManuallyFocusing) { + _isManuallyFocusing = false; + return; + } + + // Check if the focus state has actually changed + if (_isCurrentlyFocused == focus) { + return; // No state change, do nothing + } + + // Update the current focus state + _isCurrentlyFocused = focus; + + if (focus) { + _isManuallyFocusing = true; + element?.focus(); + } else { + _isManuallyFocusing = true; + element?.blur(); + } }, child: ConstrainedBox( constraints: BoxConstraints(