From b8d5e65fe834030953170bd66b068b507f9050e0 Mon Sep 17 00:00:00 2001 From: Jaime Blasco Date: Mon, 13 May 2024 21:18:02 +0200 Subject: [PATCH] fix: wait html element load (#1730) --- .../lib/src/widgets/card_field.dart | 37 +++++++++++-------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/packages/stripe_web/lib/src/widgets/card_field.dart b/packages/stripe_web/lib/src/widgets/card_field.dart index 1d86c59b7..b79d178a3 100644 --- a/packages/stripe_web/lib/src/widgets/card_field.dart +++ b/packages/stripe_web/lib/src/widgets/card_field.dart @@ -53,6 +53,8 @@ class WebCardField extends StatefulWidget { class WebStripeCardState extends State with CardFieldContext { CardEditController get controller => widget.controller; + late MutationObserver mutationObserver; + @override void initState() { // ignore: undefined_prefixed_name @@ -62,6 +64,24 @@ class WebStripeCardState extends State with CardFieldContext { ..id = 'card-element' ..style.border = 'none', ); + mutationObserver = MutationObserver((entries, observer) { + if (document.getElementById('card-element') != null) { + mutationObserver.disconnect(); + + updateCardDetails( + const CardFieldInputDetails(complete: false), + controller, + ); + element = WebStripe.js + .elements(createElementOptions()) + .createCard(createOptions()) + ..mount('#card-element') + ..onBlur(requestBlur) + ..onFocus(requestFocus) + ..onChange(onCardChanged); + } + }); + mutationObserver.observe(document, childList: true, subtree: true); initStripe(); super.initState(); } @@ -80,19 +100,6 @@ class WebStripeCardState extends State with CardFieldContext { dev.log('WARNING! Initial card data value has been ignored. \n' '$kDebugPCIMessage'); } - ambiguate(WidgetsBinding.instance)?.addPostFrameCallback((timeStamp) { - updateCardDetails( - const CardFieldInputDetails(complete: false), - controller, - ); - element = WebStripe.js - .elements(createElementOptions()) - .createCard(createOptions()) - ..mount('#card-element') - ..onBlur(requestBlur) - ..onFocus(requestFocus) - ..onChange(onCardChanged); - }); } }); } @@ -162,8 +169,7 @@ class WebStripeCardState extends State with CardFieldContext { return js.CardElementOptions( style: { 'base': { - if (textColor != null) - 'color': '${colorToCssString(textColor)}' + if (textColor != null) 'color': '${colorToCssString(textColor)}' } }, hidePostalCode: !widget.enablePostalCode, @@ -191,6 +197,7 @@ class WebStripeCardState extends State with CardFieldContext { void dispose() { detachController(controller); element?.unmount(); + mutationObserver.disconnect(); super.dispose(); }