How to implement In App Purchases in Flutter

Salman Shaikh
Canadiv’s Technology and Design
3 min readJun 1, 2023

Trying to implement in_app_purchases in flutter app.

Here’s a quick solution.

State Changing and UI is not shown in this please try to implement that on your own.

The Code related to IAP is explained here.

Add this in pubspec.yaml

in_app_purchase: ^latest_version

to know latest version get it from here.

or is your using vs code open palette then dart > add dependencies.

in_app_purchase.

1: Setup

Create an account in app store and play store respectively and fill needed data and create products as required. (remember the product ids)

Remember

Consumables are products that can be purchased multiple times.

&

Non consumables are products that are like subscriptions, etc.

2: Initializing the listener

Create this variables available in the whole widget.

final InAppPurchase _iap = InAppPurchase.instance;
late StreamSubscription subscription;
List<PurchaseDetails> purchases = [];

In the initState of whatever state mangement you are using we will add a Listener.

// await getUserProducts();
// given in Details in 3rd step
final Stream<List<PurchaseDetails>> purchaseUpdated = _iap.purchaseStream;
subscription =
purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) {
purchases = purchaseDetailsList;
_listenToPurchaseUpdated(purchaseDetailsList);
}, onDone: () {
subscription.cancel();
}, onError: (Object error) {
// handle error here.
});

and the method _listenToPurchaseUpdated we add what happens on product status chaging.

TIP: I am using BotToast to show status changes you can handle db calls or UI changes there.

Future<void> _listenToPurchaseUpdated(
List<PurchaseDetails> purchaseDetailsList) async {
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.status == PurchaseStatus.pending) {
// showPendingUI();
} else {
if (purchaseDetails.status == PurchaseStatus.error) {
// handleError
// print(purchaseDetails.error!);
// BotToast.showText(text: purchaseDetails.error.toString());
} else if (purchaseDetails.status == PurchaseStatus.purchased) {
final bool valid = hasUserPurchased(purchaseDetails.productID);
if (valid) {
// This shows that the product is in the user productsList.
// BotToast.showText(text: 'Valid');
}
}
if (purchaseDetails.pendingCompletePurchase) {
// is the product purchase is pending we will try to buy it.
// await _iap.completePurchase(purchaseDetails);
// buyProductDBCall
// BotToast.showText(text: 'Purchase Complete');
}
}
}
}

In the above code we are checking status and showing UI accordingly.

TIP: Can have to make changes as your project might need in the UI.

here is the method hasUserPurchased.

bool hasUserPurchased(String productID) {
for (var purchase in purchases) {
if (purchase.productID == productID) {
return true;
}
}
return false;
}

3: Get Products

Now we need all the product ids we create on the stores.

Future<void> getUserProducts() async {
try {
Set<String> ids = {
'id1',
'id2'
};
ProductDetailsResponse response = await _iap.queryProductDetails(ids);
// Show Products in UI
// you can show response.productDetails
// use productDetails as List of data to show in UI.
} catch (e) {
print("getUserProductsError:: $e");
}
}

You can call the method in the initState.

I have already written it in above(in the 2nd step) you just have to uncomment it.

4: Make Purchase

Now just we have to add this on the onTap or onPressed method of UI.


void buyProduct(String id) async {
loading = true;
final response = await _iap.queryProductDetails({id});
final prod = response.productDetails[0];
final PurchaseParam purchaseParam = PurchaseParam(productDetails: prod);
await _iap.buyNonConsumable(purchaseParam: purchaseParam);
// if products are consumables.
//await _iap.buyConsumable(purchaseParam: purchaseParam);
}

call this method and pass id of the product.

TIP: if you have added consumable change the

_iap.buyNonConsumable to _iap.buyConsumable .

This is how you can add in app purchases in your uniquely developed Flutter Applications.

Follow and stay connected with Canadiv Publication to stay informed about valuable insights and the most current trends within the development ecosystem.
Follow Us:
LinkedIn | Instagram

--

--