1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] java.lang.NullPointerException on flutter in app purchase package?

Discussão em 'Mobile' iniciado por Stack, Novembro 7, 2024 às 13:13.

  1. Stack

    Stack Membro Participativo

    I am trying to integrate in_app_purchase package into my flutter projects. I am using this package because I have my own backend server for verifying purchase. But after integrating I am getting one error. I try to search on the internet but not getting any similar issues, what I am facing. Please from this community help me.

    Following is my code-

    class SubscriptionPage extends StatefulWidget {
    const SubscriptionPage({super.key});

    @override
    State<SubscriptionPage> createState() => _SubscriptionPageState();
    }

    class _SubscriptionPageState extends State<SubscriptionPage> {
    final InAppPurchase _inAppPurchase = InAppPurchase.instance;
    late StreamSubscription<List<PurchaseDetails>> _subscription;

    //Product Listing
    static const List<String> _productIds = [
    'com.fitnesschallengeuk.subscription'
    ];

    @override
    void initState() {
    final Stream<List<PurchaseDetails>> purchaseUpdated =
    _inAppPurchase.purchaseStream;
    _subscription =
    purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) {
    if (mounted) {
    _listenToPurchaseUpdated(purchaseDetailsList, context);
    }
    }, onDone: () {
    _subscription.cancel();
    }, onError: (Object error) {
    if (mounted) {
    showSnackBar(context, 'Something went wrong', Severity.error);
    }
    });
    super.initState();
    }

    Future<Subscription> getProducts() async {
    final bool isAvailable = await _inAppPurchase.isAvailable();
    if (!isAvailable) {
    return Subscription(
    isAvailable: isAvailable,
    products: [],
    notFoundIds: [],
    );
    }
    final ProductDetailsResponse productDetailResponse =
    await _inAppPurchase.queryProductDetails(_productIds.toSet());

    if (productDetailResponse.error != null) {
    throw Exception(productDetailResponse.error!.message);
    }
    return Subscription(
    isAvailable: isAvailable,
    products: productDetailResponse.productDetails,
    notFoundIds: productDetailResponse.notFoundIDs,
    );
    }

    @override
    void dispose() {
    _subscription.cancel();
    super.dispose();
    }

    @override
    Widget build(BuildContext context) {
    var media = MediaQuery.of(context).size;
    return Scaffold(
    appBar: const BasicAppBar(
    title: 'Subscription',
    isBack: true,
    level: '3',
    ),
    body: QueryBuilder(
    query: Query(
    key: ['subscription'],
    queryFn: () => getProducts(),
    config: QueryConfig(
    storeQuery: false,
    cacheDuration: const Duration(milliseconds: 500),
    ),
    ),
    builder: (context, state) {
    if (state.status == QueryStatus.loading) {
    return const Center(
    child: SizedBox(
    width: 25,
    height: 25,
    child: CircularProgressIndicator(
    color: AppColors.primaryOrange,
    strokeWidth: 3,
    ),
    ),
    );
    }
    if (state.status == QueryStatus.error) {
    return SizedBox(
    width: media.width,
    child: Text(
    state.error.toString(),
    style: const TextStyle(
    fontSize: 14,
    fontWeight: FontWeight.w500,
    color: Colors.red,
    ),
    textAlign: TextAlign.center,
    ),
    );
    }
    final product = state.data!.products[0];
    return Padding(
    padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 10),
    child: SizedBox(
    width: media.width,
    child: Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: [
    Text(
    product.title
    .replaceAll(
    '(com.fitnesschallengeuk.fitness_challenge_uk (unreviewed))',
    '')
    .trim(),
    style: const TextStyle(
    fontSize: 16,
    ),
    textAlign: TextAlign.center,
    ),
    SizedBox(height: media.height * 0.06),
    SvgPicture.asset(
    AppVectors.subscriptionIcon,
    width: 260,
    ),
    SizedBox(height: media.height * 0.065),
    Text(
    product.price,
    style: const TextStyle(
    fontSize: 35,
    fontWeight: FontWeight.w600,
    ),
    ),
    const Text('/month'),
    SizedBox(height: media.height * 0.06),
    Text(
    product.description,
    style: const TextStyle(
    fontSize: 13,
    ),
    textAlign: TextAlign.center,
    ),
    const Spacer(),
    const Text(
    'Are you want to subscribe?',
    style: TextStyle(
    fontSize: 14,
    fontWeight: FontWeight.w600,
    ),
    textAlign: TextAlign.center,
    ),
    const SizedBox(height: 30),
    BasicAppButton(
    title: 'Subscribe',
    onPressed: () {
    final PurchaseParam param =
    PurchaseParam(productDetails: product);
    _inAppPurchase.buyConsumable(purchaseParam: param);
    },
    level: '3',
    ),
    const SizedBox(height: 20),
    ],
    ),
    ),
    );
    },
    ),
    );
    }

    _listenToPurchaseUpdated(
    List<PurchaseDetails> purchaseDetailsList, BuildContext context) async {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
    if (purchaseDetails.status == PurchaseStatus.pending) {
    showSnackBar(
    context,
    'You are purchasing a subscription',
    Severity.success,
    );
    } else if (purchaseDetails.status == PurchaseStatus.error) {
    showSnackBar(
    context,
    'Your purchased failed!',
    Severity.error,
    );
    } else if (purchaseDetails.status == PurchaseStatus.purchased) {
    print('ProductId: ${purchaseDetails.productID}');
    print('PurchaseId: ${purchaseDetails.purchaseID}');
    print('TransactionId: ${purchaseDetails.transactionDate}');
    print(
    'Local: ${purchaseDetails.verificationData.localVerificationData}');
    print(
    'Server: ${purchaseDetails.verificationData.serverVerificationData}');
    print('Source: ${purchaseDetails.verificationData.source}');
    showSnackBar(
    context,
    'Your purchase is successfully',
    Severity.success,
    );
    }
    }
    }
    }


    Now I am facing one error on my debug_console-

    W/BillingLogger( 7906): Unable to log.
    W/BillingLogger( 7906): java.lang.NullPointerException


    Here is the full screenshot-

    Click to see image

    Continue reading...

Compartilhe esta Página