diff --git a/packages/stripe_web/lib/src/widgets/platform_pay_button.dart b/packages/stripe_web/lib/src/widgets/platform_pay_button.dart index fe811abe..04c78a75 100644 --- a/packages/stripe_web/lib/src/widgets/platform_pay_button.dart +++ b/packages/stripe_web/lib/src/widgets/platform_pay_button.dart @@ -32,6 +32,36 @@ class WebPlatformPayButton extends StatefulWidget { } class _WebPlatformPayButtonState extends State { + final web.HTMLDivElement _divElement = web.HTMLDivElement() + ..id = 'platform-pay-button'; + + late final web.MutationObserver mutationObserver = web.MutationObserver( + ((JSArray entries, web.MutationObserver observer) { + if (web.document.getElementById('platform-pay-button') != null) { + mutationObserver.disconnect(); + + PaymentRequest paymentRequest = WebStripe.js + .paymentRequest((widget.paymentRequestCreateOptions).toJS()); + + paymentRequest.canMakePayment().then((value) { + WebStripe.js.elements().createPaymentRequestButton( + JsPaymentRequestButtonElementCreateOptions( + paymentRequest: paymentRequest.js, + style: JsPaymentRequestButtonElementStyle( + paymentRequestButton: PaymentRequestButtonStyleOptions( + theme: theme(Theme.of(context).brightness), + type: type, + height: '${constraints.maxHeight}px', + )))) + ..on('click', (event) { + event.toDart['preventDefault'](); + widget.onPressed(); + }) + ..mount('#platform-pay-button'.toJS); + }); + } + }.toJS)); + BoxConstraints get constraints => widget.constraints ?? const BoxConstraints.expand(height: kPlatformPayButtonDefaultHeight); @@ -40,8 +70,13 @@ class _WebPlatformPayButtonState extends State { void initState() { // ignore: undefined_prefixed_name ui.platformViewRegistry.registerViewFactory('stripe_platform_pay_button', - (int viewId) => web.HTMLDivElement()..id = 'platform-pay-button'); - _initButton(); + (int viewId) => _divElement); + + mutationObserver.observe( + web.document, + web.MutationObserverInit(childList: true, subtree: true), + ); + super.initState(); } @@ -58,30 +93,6 @@ class _WebPlatformPayButtonState extends State { ); } - _initButton() { - WidgetsBinding.instance.addPostFrameCallback((timeStamp) { - PaymentRequest paymentRequest = WebStripe.js - .paymentRequest((widget.paymentRequestCreateOptions).toJS()); - - paymentRequest.canMakePayment().then((value) { - WebStripe.js.elements().createPaymentRequestButton( - JsPaymentRequestButtonElementCreateOptions( - paymentRequest: paymentRequest.js, - style: JsPaymentRequestButtonElementStyle( - paymentRequestButton: PaymentRequestButtonStyleOptions( - theme: theme(Theme.of(context).brightness), - type: type, - height: '${constraints.maxHeight}px', - )))) - ..on('click', (event) { - event.toDart['preventDefault'](); - widget.onPressed(); - }) - ..mount('#platform-pay-button'.toJS); - }); - }); - } - PaymentRequestButtonType get type { switch (widget.type) { case PlatformButtonType.buy: