Neli
Neli

Reputation: 741

flutter in_app_purchase purchaseUpdatedStream listen event not firing

Buying a product works fine but when I try to get the bought products on startup of the app the listening is not working.

The logger.i("purchaseInit") message is not displayed.

purchaseInit() {

    StreamSubscription<List<PurchaseDetails>> _subscription;

    final Stream purchaseUpdated = InAppPurchase.instance.purchaseStream;

    _subscription = purchaseUpdated.listen((purchaseDetailsList) {
      logger.i("purchaseInit"); // not showing up
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
    }, onError: (error) {
      // handle error
    });}


void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) {

    purchaseDetailsList.forEach((PurchaseDetails purchaseDetails) async {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        logger.i("_showPendingUI()");
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          logger.i(purchaseDetails.error);
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          logger.i(purchaseDetails);
        }
        if (purchaseDetails.pendingCompletePurchase) {
          await InAppPurchase.instance.completePurchase(purchaseDetails);
        }
      }
    });
  }

Upvotes: 0

Views: 1434

Answers (1)

Tim Br&#252;ckner
Tim Br&#252;ckner

Reputation: 2099

It seems, you are just listening to purchases by subscribing to the stream. But previous purchases are not emitted by the stream upon startup of the app or upon subscribing to it.

In order to get a list of previous purchases, you must trigger a restore.

await InAppPurchase.instance.restorePurchases();

This will re-emit the previous purchases of non-consumable products and your listener will be able to handle them.

However, I suggest that you try to keep track of what the user purchased yourself and only call restorePurchases() if necessary.

https://pub.dev/packages/in_app_purchase#restoring-previous-purchases

Upvotes: 2

Related Questions