Skip to content

Commit

Permalink
fix: wait html element load (#1730)
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesblasco authored May 13, 2024
1 parent 7f3f8a8 commit b8d5e65
Showing 1 changed file with 22 additions and 15 deletions.
37 changes: 22 additions & 15 deletions packages/stripe_web/lib/src/widgets/card_field.dart
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ class WebCardField extends StatefulWidget {
class WebStripeCardState extends State<WebCardField> with CardFieldContext {
CardEditController get controller => widget.controller;

late MutationObserver mutationObserver;

@override
void initState() {
// ignore: undefined_prefixed_name
Expand All @@ -62,6 +64,24 @@ class WebStripeCardState extends State<WebCardField> 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();
}
Expand All @@ -80,19 +100,6 @@ class WebStripeCardState extends State<WebCardField> 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);
});
}
});
}
Expand Down Expand Up @@ -162,8 +169,7 @@ class WebStripeCardState extends State<WebCardField> with CardFieldContext {
return js.CardElementOptions(
style: {
'base': {
if (textColor != null)
'color': '${colorToCssString(textColor)}'
if (textColor != null) 'color': '${colorToCssString(textColor)}'
}
},
hidePostalCode: !widget.enablePostalCode,
Expand Down Expand Up @@ -191,6 +197,7 @@ class WebStripeCardState extends State<WebCardField> with CardFieldContext {
void dispose() {
detachController(controller);
element?.unmount();
mutationObserver.disconnect();
super.dispose();
}

Expand Down

0 comments on commit b8d5e65

Please sign in to comment.