Creating In-App Purchases using Flutter for Android and iOS

Tiempo de lectura: 2 minutos

Perfecto, vamos a hacer un tutorial paso a paso para implementar in_app_purchase en Flutter y crear un widget de compras. Te lo voy a estructurar de manera clara para que puedas integrarlo directamente.

Autumn - pexels

En tu pubspec.yaml agrega:

dependencies: flutter: sdk: flutter in_app_purchase: ^5.0.0 # check the latest version on pub.dev 

Then run:

flutter pub get 

Import the package

In your Dart file where you will make the purchase:

import 'package:flutter/material.dart'; import 'package:in_app_purchase/in_app_purchase.dart'; 

Initialize InAppPurchase

Before using purchases, initialize the instance:

final InAppPurchase iap = InAppPurchase.instance;

Create a Widget of Purchases

We will create a PurchaseWidget that lists products and allows purchases.

<

pre class=”EnlighterJSRAW” data-enlighter-language=”generic” data-enlighter-theme=”” data-enlighter-highlight=”” data-enlighter-linenumbers=”” data-enlighter-lineoffset=”” data-enlighter-title=”” data-enlighter-group=””>class PurchaseWidget extends StatefulWidget { @override _PurchaseWidgetState createState() => _PurchaseWidgetState();}class _PurchaseWidgetState extends State { final InAppPurchase iap = InAppPurchase.instance; bool available = false; List products = []; List purchases = []; @override void initState() { super.initState(); initialize(); } Future initialize() async { available = await iap.isAvailable(); if (available) { // Define your product IDs const Set kIds = {‘product1’, ‘product2’}; final ProductDetailsResponse response = await iap.queryProductDetails(kIds); if (response.error == null) { setState(() { products = response.productDetails; }); } // Listen to purchases iap.purchaseStream.listen((purchases) { for (var purchase in purchases) { handlePurchase(purchase); } }); } } void handlePurchase(PurchaseDetails purchase) { if (purchase.status == PurchaseStatus.purchased) { print(“Purchase completed: ${purchase.productID}”); } else if (purchase.status == PurchaseStatus.error) { print(“Error in purchase: ${purchase.error}”); } } void buyProduct(ProductDetails productDetails) { final PurchaseParam purchaseParam = PurchaseParam(productDetails: productDetails); iap.buyConsumable(purchaseParam: purchaseParam); } @override Widget build(BuildContext context) { if (!available) { return Center(child: Text(“Purchases not available”)); } return ListView.builder( itemCount: products.length, itemBuilder: (context, index) { final product = products[index]; return Card( child: ListTile( title: Text(product.title), subtitle: Text(product.description), trailing: TextButton( child: Text(product.price), onPressed: () =>

Leave a Comment