Flutter: get past purchases on Android

Issue

I’m refactoring in_app_purchases and I’m trying to get the past purchases. According to the documentation:

The InAppPurchaseConnection.queryPastPurchases method has been
removed. Instead, you should use InAppPurchase.restorePurchases. This
method emits each restored purchase on the
InAppPurchase.purchaseStream, the PurchaseDetails object will be
marked with a status of PurchaseStatus.restored

But the example they provide doesn’t get the past purchases, it adds the one you buy at that moment.

I moved from this:

final QueryPurchaseDetailsResponse purchaseResponse =
        await _connection.queryPastPurchases();

to this:

final Stream<List<PurchaseDetails>> purchaseUpdated = inAppPurchase.purchaseStream;

print(purchaseUpdated.toList());

I tried the above but the list is empty and for sure my user has purchases as I can show here when I try to buy the same version I bought before:
enter image description here

How could get a List from previous purchases?

Solution

You have to listen to the purchaseStream like this code in the example:

    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;
    _subscription = purchaseUpdated.listen((purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
    }, onError: (error) {
      // handle error here.
    });

All the purchased items will be added to this stream, so you need to add all the results to your list like below:

    final List<PurchaseDetails> purchasedList = [];
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;
    _subscription = purchaseUpdated.listen((purchaseDetailsList) {

      purchasedList.addAll(purchaseDetailsList);

    }, onDone: () {
      _subscription.cancel();
    }, onError: (error) {
      // handle error here.
    });

Now you can use purchasedList as previous purchases. By the way, all the newly purchased items will be also added to that stream and purchasedList.

UPDATE: After the above steps, you need to call _inAppPurchase.restorePurchases() to get the previous purchases, all the previous purchases will be added to purchasedList by the purchaseStream.

Answered By – Softs.dev

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.