Home Blog Page 21

10 tips to improve programming logic skills

0
How to Improve Programming Logic

Here are 10 tips on:

How to improve logical thinking for programming.

1. Keep the concept clear

Always Keep your base strong, I mean to say keep basic of a programming language strong. In order to solve any real world problem by coding you should be cleared with the concepts.

2. Be Consistent

Is you are beginner in coding/programming practicising coding on daily will build you core. Take one problem: solve it, There is a quote : “Practice Makes a man perfect”. The same applies in programming world.

Practicing consistently will improve you coding and logic thinking.

3. Think with a Pen and Paper

Then you have coding don’t directly start typing on you IDE, “Programming is Thinking first, Typing later”. Think clearly about the problem and how you can solve it, and in how many ways. To find a best ways use Pen & Paper.

4. Learn New Things daily

Keep yourself updated with latest technologies arrived in software world, Any courier field you choose of has a life long learning. You aim in life should be in solving latest problem that come in your life or in code, don’t be stuck into a old pattern or algorithm logic and search for success.

5. Mathematical Concepts should be strong

In programming, Mathematics plays information role when applying logic while coding. Be good in Maths took to improve your programming skills.

No need to be super strong in mathematics but you should at least have high school level math knowledge.

6. Build Projects

The best thing to do to improve logic in coding is by building real project by yourself like a full stack developer who build complete project by himself by this you will get good knowledge in frontend as well as backend.

All you need to do is search for a company who assigns freelances projects.

7. Preparations of notes

Making Notes is boring, But preparing it will makes you learn new technology and you will remember for a long and also the concept will be clearer as you theoretically write in on a book.

8. Break the problem into smaller sub-tasks.

Once you get a real time projects to be done, break a complete project into small small tasks. Like this you can learn faster and complete it sooner.

9. Participate in coding events

If there is any coding competition going on in your town, take part in those coding event that will make your coding logic to build faster, And you will come across to many programming and explore the coding world more.

10. Be Patience in learning

In life to achieve anything you need to be patience. Likewise to develop coding logic, you have be consistent in practicing and patience.

I seen many people who comes into programming and after few days they leave the field just because they go stuck into a problem.

AI-generated images in Flutter using OpenAI

0
OpenAI Image Generation In Flutter

Hi Guy’s Welcome to Proto Coders Point. In this Flutter Article we will make use of OpenAI DALL-E 2 API and explore the super power of OpenAI, By creating an flutter application that can convert a given Text into an AI image. You will learn how to we make use of OpenAI API to generate a unique & stunning AI realistic image , and how to implement it into our Flutter app to generate AI Image from a given Text Sentence.

In below Flutter Video Tutorial on Youtube, I have cover everything from setting up the API, to making API calls and displaying the generated images in the flutter app. By the end of this tutorial, You will learn how to use OpenAI DALL-E 2 API to convert text to AI generated image and show it in your own flutter app and create a beautiful & realistic AI images.

Creating an Account

Step 1: Create an account in openai.com

In browser, search for openai.com and SignIn using Google account or any other account.

Step 2: You need to activity a billing

Added your credit card for billing, Initially OpenAI gives you $15 free to generate images from Text. Then you will be charged.

Here are charges depending on the Image Size you order for:

RESOLUTIONPRICE
1024×1024$0.020 / image
512×512$0.018 / image
256×256$0.016 / image

Step 3: Generate a openai API key

Create a Flutter App to Generate an AI Image from Text by using open ai image generation

Implementing OpenAI in Flutter App

Step 1: Install http package

As we are going to make internet call in our flutter app generate an AI Image to open ai API, we need a http package to do so.

In flutter project, open pubspec.yaml file and under dependencies section add http package.

dependencies:
  flutter:
    sdk: flutter
  http:

Step 2: Import the http class

In main.dart file of flutter project, Import http.dart file

import 'package:http/http.dart' as http;

Step 3: Create a async function

Now, Create a function generateAIImage() that makes a HTTP call to OpenAI DALL-E Image Generation API by passing desired Text of which you want AI to generate a Image.

void generateAIImage() async{
    if(inputText.text.isNotEmpty){
      
      var data ={
        "prompt": inputText.text,
        "n": 1,
        "size": "256x256",
      };
      
      var res = await http.post(Uri.parse(url),
          headers: {"Authorization":"Bearer ${apikey}","Content-Type": "application/json"},
          body:jsonEncode(data));

      var jsonResponse = jsonDecode(res.body);

      image = jsonResponse['data'][0]['url'];
      setState(() {

      });
      
    }else{
      print("Enter something");
    }
  }

The above function will make a http post request to openai, so in this http request we are passing the data and in header we are passing openai authorization api key.

In request body we need to pass this parameters

prompt: a Text of which AI should generate an image.

n: Number of different image to be generate of the given text.

size: The size of the generated images.

Step 4: Show the image response in app

Once the above function return the response, we need to parse the JSON response from the API and extract only url of the generate image.

And thus make use of Image.network() flutter widget to display the AI generated image in flutter app.

Complete Source Code – Flutter open ai image generation

main.dart

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController inputText = TextEditingController();
  String apikey = 'tsk-nTRcf1113XPQht7r22T3Bvadapavlb5kFJYz1yz5b4xifuyzpoiyom2ooNIQehy';
  String url = 'https://api.openai.com/v1/images/generations';
  String? image;
  void getAIImage() async{
    if(inputText.text.isNotEmpty){
      
      var data ={
        "prompt": inputText.text,
        "n": 1,
        "size": "256x256",
      };
      
      var res = await http.post(Uri.parse(url),
          headers: {"Authorization":"Bearer ${apikey}","Content-Type": "application/json"},
          body:jsonEncode(data));

      var jsonResponse = jsonDecode(res.body);

      image = jsonResponse['data'][0]['url'];
      setState(() {

      });
      
    }else{
      print("Enter something");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Open AI DALL.E"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            image != null ? Image.network(image!,width: 256,height: 265) : Container(child: Text("Please Enter Text To Generate AI image"),),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: TextField(
                controller: inputText,
                decoration: InputDecoration(
                    hintText: "Enter Text to Generate AI Image",
                    filled: true,
                    fillColor: Colors.blue.shade100,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: BorderSide.none,
                    )
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          getAIImage();
        },
        tooltip: 'Generate AI Image',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

App Lifecycle In Flutter – A complete guide

0
Flutter LifeCycle
Flutter LifeCycle

Communication between UI widgets and Flutter life cycle methods.

The Flutter App’s lifecycle displays how the application will modify its State. It aids in comprehending the principle underlying the easy development of our apps. Since everything in Flutter is a widget, we should consider Flutter’s widget before considering its lifecycle.

flutter lifecycle

The Lifecycle of an Flutter App

The Lifecycle of a Flutter App shows how the app will alter its State. It aids in comprehending the idea underlying the fluid movement of our applications. I want to impart everything I’ve learned about creating widgets in Flutter. Let’s start…

Widgets refer to all of the user interface elements that are visible on the screen. Based on the widget’s capacity to be reloaded during runtime, widgets may be roughly classified into two classes.

Flutter has majorly two types of widgets :

  • Stateless
  • Stateful Widget.

We must comprehend the differences between the two widgets before learning about the Lifecycle.

1. Stateless Widget :

Stateless In Flutter, a widget is a component whose state, once generated, cannot be altered; examples include variables, buttons, icons, and other components whose states cannot be altered in order to access data. replaces the build method and then returns a widget. When the UI depends on data contained within the object itself, we utilize it. In short , Stateless widgets are ones that do not alter dynamically during execution and do not need managing the state.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Container();
  }
}

2. Stateful Widget :

A stateful widget keeps track of data and reacts to everything the data does while being used by the application. It is rendered several times over its lifespan since it is a changeable widget.

When a user dynamically changes the application screen, we use this. The fact that this widget features a status widget, which lets everyone know when anything has changed on our screen, makes it the most significant of all the widgets. In short , Stateful widgets are ones that keep track of the current state and allow for dynamic runtime changes to the user interface.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Thus, as “Stateful Widgets” are those that handle the State, we will focus on them when we talk about the LifeCycle of Flutter.

Lifecycle Flow Chart For Flutter App.

Lifecycle Flow Chart For Flutter App

Stages of Flutter App Lifecycle:

The state and how it changes affect the life cycle. We may describe the flutter life cycle based on a stateful widget’s state. The life cycle stage:

  • createState()
  • initState()
  • didChangeDependencies()
  • build()
  • didUpdateWidget()
  • setState()
  • deactivate()
  • dispose()

Due to the creation and re-construction of the Widgets and their State, you’ll see a lot more “states” for the making than the destruction.Let’s explore more into life cycle stages:

1)  createState()

The Flutter framework will give instructions to construct a method called createState() in override when we create a stateful widget. An instance of the state that this method is linked with will be returned.
I used the stateful class name “MyHomepage” in this life cycle example. When the ‘buildContext’ is assigned and located on a tree, all widgets’ bool mounted values change to true. Until dispose is called, the value will be retained.
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState(); 
}

2) initState()

This tactic is taken into account when the Widget is created in an engaging manner and is called precisely once for each State object. The initState() function will execute any characterised or added code first, even before the widgets are constructed.

This function must call super.initState(), which executes the parent widget’s initState (Stateful widget). Your variables, objects, streams, AnimationController, and other items may all be initialised here.

@override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

3)  didChangeDependencies()

When the widget is created for the first time, this function is invoked immediately after initState(). If a modification is required and your StatefulWidgets depend on an InheritedWidget, they will call again.There aren’t many functions you can include, such as variable re-initializations and API requests reliant on parent data changes.

@override
void didChangeDependencies() {
  super.didChangeDependencies()
}

4) build()

This approach serves as the primary technique since it is essential to the presentation of all widgets. Every time we need to display UI Widgets on the screen, it is called.

The Flutter framework changes the build() method whenever you need to update your UI or, alternatively, on the off chance that you hit hot-reload!. You may use setState(), which instructs the framework to once again run the form function, if you need to specifically redesign the UI whenever any information is changed.

@override
Widget build(BuildContext context) {
  return Container()
}

5) didUpdateWidget()

When the parent Widget makes a modification and the UI has to be redrew, it will be invoked. It basically runs every time we hot reload the programme to check for widget changes.

When a parent widget has to edit a child widget with a comparable Runtime Type because the parent’s properties or designs have changed, didUpdateWidget is triggered. This turns away from the new widget and accepts the arrangement modifications made by it.

@protected
void didUpdateWidget(MyApp oldWidget) {
 super.didUpdateWidget(oldWidget);
}

6)  setState()

The framework schedules a build for this State of object after being informed by the setState() function that the internal state of the object has changed in a way that might affect the UI.

Calling this function after the framework calls dispose is incorrect.

void function(){
 setState(() {});
}

7)  deactivate()

This approach is taken into account when the State is eliminated from the tree, but it may also be re-inserted into the tree at a different location.

This approach is taken into account when the widget is not yet connected to the Widget Tree but may very likely be added at a later time. The part when you utilise Navigator is the finest example of this. Deactivate is used when a client wants to return to the previous screen after pushing to the next one, in which case the widget will once more be added to the tree.

@override
void deactivate(){
 super.deactivate();
}

8)  dispose()

This approach, which is crucial, basically runs counter to the initState() function. It is taken into account when the item and its State ought to be permanently removed from the Widget Tree and won’t ever reassemble.

You may dismiss documents, cancel timers, dispose of animation controls, unsubscribe from streams, and more here. You can ultimately provide each and every asset in this plan. Currently, if the widget is later added to the widget tree again, the entire lifespan will be repeated.

When removing something permanently, such as when releasing a resource produced by an item or stopping animation, we employ this technique.

@override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

Flutter App LifeCycle – Code Example

Create a new dart file called widget_lifecycle_demo.dart inside the lib folder. And paste below code into this.

import 'package:flutter/material.dart';
class LifeCycleDemoScreen extends StatefulWidget {
 @override
 _LifeCycleDemoScreen State createState() => _LifeCycleDemoScreen State();
}

class _LifeCycleDemoScreen State extends State<LifeCycLifeCycleDemoScreen leExm> with WidgetsBindingObserver {

 @override
 void initState() {
   super.initState();
   WidgetsBinding.instance!.addObserver(this);
   print("initState");
 }

 @override
 void didChangeAppLifecycleState(AppLifecycleState state) {
   super.didChangeAppLifecycleState(state);
   print('AppLifecycleState: $state');
 }

 @override
 void dispose() {
   WidgetsBinding.instance!.removeObserver(this);
   super.dispose();
 }

 @override
 void deactivate() {
   // TODO: implement deactivate
   print("deactivate");
   super.deactivate();
 }

 int _counter = 0;

 void _incrementCounter() {
   setState(() {
     _counter++;
   });
 }

 @override
 Widget build(BuildContext context) {
   print("build");
   return Scaffold(
     appBar: AppBar(title: Text("Flutter Widget Lifecycle")),
     body: Center(
       child: Column(
         mainAxisAlignment: MainAxisAlignment.center,
         children: <Widget>[
           Text(
             'You have pushed the button this many times:',
           ),

           Text(
             '$_counter',
             style: Theme.of(context).textTheme.headline4,
           ),
           SizedBox(height: 8.0,),
         ],
       ),
     ),
     floatingActionButton: FloatingActionButton(
       onPressed: _incrementCounter,
       tooltip: 'Increment',
       child: Icon(Icons.add),
     ),
   );
 }
}

Conclusion

I’ve described the fundamentals of the App Lifecycle in a flutter in the post; you may change the code to suit your preferences. This was a brief introduction from my end to the app life cycle on user interaction, and it functions using Flutter.

I’m hoping that this post will provide you enough knowledge to set up the App Lifecycle in your Flutter applications. We’ll demonstrate the Flutter app’s lifecycle for you. This blog post looked at the flutter app’s lifetime. I’m hoping that this blog will better your understanding of the life cycle. Please give it a try.

Thank you for reading this post.  

Clap 👏 If you find this post useful. Have a nice day………….

Retrieving a List of Files in a Directory using Node.js

0
nodejs list files in directory

Hi Guy’s Welcome to Proto Coders Point, In this article let’s check out how to list files in a folder/directory using node.js.

In Node.js, we can make use of fs module with promises (fs.promises) to asynchronously list out all the files in a directory.

Example on how to list all files in a directory using NodeJS

Below is my nodejs project structure, which has a files folder with document such a image, text files. I want to list all the files using nodeJS code.

nodejs project structure

In NodeJS fs library module, we can make use of fs.readdir() function to get list of files in defined directory.

Here is an example on How to use fs.readdir() function in nodejs

const fs = require('fs');
const path = require('path');

const directoryPath = path.join(__dirname, 'files');  // here files is my folder name.

fs.readdir(directoryPath, (err, files) => {
    if (err) {
        return console.log(`Unable to scan directory: ${err}`);
    }
    files.forEach((file) => {
        console.log(file);
    });
});

output

nodejs example to list all files contained in a directory

In above code example, ‘path.join()’ function is used to concat path of your project directory + the directory name you provide. Then fs.readdir() function takes parameter that is the ‘directoryPath’ generated and in second argument is a callback function that will list the array of the files in the directory.

Flutter Offstage widget to hide/show any widget

0
Flutter Offstage widget

Hi Guy’s Welcome to Proto Coders Point. In this Flutter tutorial will check how to programmatically hide show widget in flutter app.

Flutter provides a inbuilt widget called “Offstage”, which is been used to hide or show any widget programmatically depending on user action/event.

Video Tutorial

Syntax of Flutter Offstage widget

 Offstage(
          offstage: true or false,
          child: <Any Child Widget>
      ),

Flutter Offstage widget has a property ‘offstage’, which accept Boolean value.

The child widget is hidden when the offstage property is set to true.

Likewise if property is set to ‘false’, the child widget is shown.

How to use OffStage Widget in flutter

Here’s an example of how to use the Offstage widget to conditionally hide or show a container with icon widget(or any widget):

 Offstage(
              offstage:isHidden ,
              child: Container(
                width: 100,
                height: 100,
                color: Colors.blue,
                child: Icon(Icons.flutter_dash,size: 70,color: Colors.black,),
              ),
       ),

In above snippet code example, The Container widget is been wrapped with Offstage widget, and will be hidden if 'isHidden' is set to true, and will be shown if the 'isHidden' value is set to false.

How to Programmatically hide/show widget in flutter using OffStage

You can also hide/show any widget depending on the state of another widget.

Complete source code on how to use Offstage widget in flutter

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Favicon',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
bool isHidden = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Offstage(
              offstage:isHidden ,
              child: Container(
                width: 100,
                height: 100,
                color: Colors.blue,
                child: Icon(Icons.flutter_dash,size: 70,color: Colors.black,),
              ),
            ),
            SizedBox(height: 20,),
            ElevatedButton(onPressed: (){
                setState(() {
                  isHidden = !isHidden;
                });
            }, child: Text(isHidden? "Show":"Hide"))
          ],
        ),
      )
    );
  }
}

Here In above example, I have used a button to toggle and show/hide widget in flutter.

Integrate In-app purchase in Flutter. (step-by-step)

0
flutter inapp purchase
inapp purchase in flutter

Hi Guy’s Welcome to Proto Coders Point. In this Flutter Article let’s learn how to Implement In-App purchase in flutter a step by step guide.

First, we’ll look at what an in-app purchase ??.

An in-app purchase (IAP) is a purchase made from within an application, most commonly a mobile app running on a smartphone or other mobile device. Software vendors can sell anything from within apps. For example, Users can buy characters, upgrade abilities, and spend real money on in-game currencies in games.

Although we always make our applications with care, they are not always free. Aside from charging a fee to upload our apps to the Play store, another way we make money is through in-app purchases. Flutter in app purchase (IAP) is a first-party Flutter package that allows developers to integrate in-app purchases from the iOS App Store or Google Play into their app. Similar functionality is provided by two other solutions: flutter in app purchase and purchases flutter.

Our goal in this article is to guide you through the in_app_purchase package.

So, why are in-app purchases necessary?

In-app purchases enable developers to provide their programmers for free. After downloading the free version, users are bombarded with advertisements for paid feature unlocks, premium version upgrades, exclusive goods for sale, and even additional applications and services. Because in-app transactions are required when selling digital content, services such as Stripe api will not be applicable in this case.

KEY LESSONS

  • In-app purchasing is the purchase of goods and services from within an app on a mobile device such as a smartphone or tablet.
  • In-app purchases enable developers to make their applications available for free.
  • Because in-app purchases are made via a mobile device, unauthorized purchases may cause security issues.

In flutter, what exactly is an in-app purchase?

An in-app purchase, or IAP, is a method of selling content to customers from within the app rather than through an online store. It could be anything from access to premium content to a competitive advantage in a mobile game. In some cases, in-app purchases can be combined with other forms of monetization. Users, for example, may choose to upgrade to a premium version in order to avoid seeing advertisements.

For Android, Google Play distinguishes two types of in-app purchases. The first is subscription — ongoing access to paid content. When users’ regular payments stop, they lose access to premium services. This paradigm is most commonly used in the distribution of corporate programmers as well as services that generate content on a consistent basis, such as online magazines.

We need a payment mechanism in our app to include a premium user feature. Payment gateway setup is a major pain. The simplest way to incorporate a payment gateway is to include in-app purchases in your app. Let’s talk about in-app purchases before we get into the code.

It was the first time I’d ever added in-app purchases to an app. I had a lot of inquiries.

How do I make the product price international?

How can I avoid hardcoding product details into my app?

How much will Google charge in commission?

The answer is that Google Play Store takes care of everything for you. And retains 30%. You get 70% of the money.

Before you continue reading, please keep in mind that this tutorial only covers the Android portion. A developer account is also required to integrate IAP, even for testing. So, before you begin, I recommend that you spend $25 and purchase a Play Store developer account.

Android Products

Consumable item: Consumable items include in-game currency. The user can repurchase them after they have been consumed.

Non-consumable item: These items can only be purchased once and provide a long-term benefit.

Subscriptions: These items provide users with benefits for a set period of time. Subscriptions to Netflix, Medium, and Spotify can be compared to these items. Unless canceled, subscriptions renew automatically.

In both the iOS and Android platforms, a subscription cannot be repurchased before it expires.

You must create items on Google Play Console based on your specifications.

Both platforms offer features like a grace period, a trial period, the ability to upgrade or downgrade a membership, and so on.

This tutorial will walk you through the process of adding subscribers to the Flutter app. In order to test the in-app purchase, your app must have an alpha release in Android.

The Value of IAPs in App Store Optimization:

IAPs are metadata components that influence the visibility of apps. They are made up of three distinct types of metadata:

IAP icon, title, and brief description

The IAP title is essential for app store optimization. It is significant because the App Store and Google Play algorithms index the names of non-consumable and subscription IAPs, respectively. If these phrases contain such keywords, the algorithms will rank the app for them. Even more importantly, the app will rank for long-tail keywords that are a combination of the phrases in the app title and the IAP title.

Integration

Step 1):  Create an Android product.

1) Go to Google Play Console.

2) Select the app for which you want to create a subscription.

3). From the Monetize > Products menu, choose Subscriptions.

4). Complete the form with the required information. The product id is the most important field in this case. The product id is a unique identifier for each product.

Any product in one subscription group can be activated, and users can upgrade and downgrade their subscriptions within the group.

Let us proceed to the next step.

Step 2):  Make a New test account.

You must test the in-app purchase flow before releasing it to the stable version. You don’t want to pay every time you purchase a product while testing the in-app purchasing flow. To begin, you must create an Android tester account. Create an Android Testing Account,

Simply follow the two steps below to create an Android testing account.

Step i). Enter the tester’s email address in the app’s license testers.

Step ii). Using the same email address, add yourself to the app’s tester list.

Follow this detailed guide to test your Google Play Billing Library integration:

Step 3): Learn About Subscription Purchases flow

The purchase flow is based on flutter_inapp_purchase

You start the app by connecting to the Google / Apple billing server. Connection establishment may fail if the billing SDK is not supported by the current OS version. After the connection is established, your app subscribes to the billing server’s PurchaseUpdateStream. The billing server notifies you via PurchaseUpdateStream of the status of every purchase made by the current user.

You load a list of all available products for the user after your app successfully subscribed to the PurchaseUpdateStream.

The user chooses a product from the list and proceeds to buy it. The following events occur now.

1) The app notifies the billing server that the current user wants to buy a product with this product id.

2) The billing Server finishes the transaction and returns the result. The response is sent to the app via PurchaseUpdateStream.

Your app will monitor the transaction’s progress and take appropriate action.

3) If the transaction was successful, your app will notify the back end that this user successfully purchased a product, and here is the purchase token I received from the billing server. The app’s back end will validate the purchase with the billing server before providing any benefits to the user. Following successful validation, your app’s back end will mark the current user as a premium user and respond to your app.

4) Your application must now complete the transaction with the billing server. The transaction’s completion notifies the billing server that the product has been successfully delivered to the user. The way transactions are completed differs between Android and iOS. In Android, you simply need to complete the successful transaction. In iOS, regardless of transaction state, you must complete all transactions. If you do not complete the transaction on Android, Google will refund the purchase amount as if the transaction failed.When the user reopens the app after it has crashed or if a network problem occurs during the transaction, your app will be notified of all uncompleted transactions via the PurchaseUpdateStream. As a result, you can go ahead and buy the product.

5) Based on the response from the app’s back end, you will show the user a specific screen.

Let’s move on to our final and most important step: integrating in-app purchases into Flutter.

Step 4) : Connect Flutter to In-App Purchases.

This is the most important metric. You will be in charge of the payment and purchase information. You must deal with any and all possible exceptions that may arise during the course of a purchase.

You must deal with any and all possible exceptions that may arise when purchasing a product.

If you understand the flow of subscription purchase, this step will make more sense to you.

So let’s get started coding.

Step 1) :: Include an in-app purchase package

in_app_purchase: ^any

Step 2) :: Run flutter package command in the root directory of your app.

Step 3) :: Following that, we must grant certain permissions so that the Play Store recognises that this app contains in-app purchases. In your app/src/main/AndroidManifest.xml, include the billing permission.

<uses-permission android:name=”com.android.vending.BILLING”>;

Let us now create a sample app for Google Play. Make a signed apk file for your Flutter app. The official flutter dev documentation includes instructions for creating a release apk. Remember that the Play Store uses your app package name (application ID) to identify your in-app items.

Let’s make some in-app items now. Go to Store Presence > Managed Products > In-app Products to get started. CREATE MANAGED PRODUCTS is the option to choose.

Make an in-app product in the Play Console.

The Product ID is unique and cannot be changed once it has been generated. You will not be able to create another product with the same id for the same app if you delete it. So proceed with caution.

Set a prize for any specific country’s product.

Following that, we will create the flutter code that will initiate the purchase and deliver the goods after payment is received.

Make a list of all the product IDs. Because this is a set, pay attention to the order of the product ids. They’ll be listed alphabetically.

var _productIdList = {'product1', 'product2', 'product3'};

Define the instance :

final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  List<ProductDetails> _products = <ProductDetails>[];

_products is an array of ProductDetails objects. They are associated with each product ID and contain data such as packageName, purchaseTime, and so on. In your initState function, initialize these variables and assign a handler to them.

@override
  void initState() {
    ///Step: 1
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;
    _subscription = purchaseUpdated.listen((purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
    }, onError: (Object e) {
      debugPrint("error :${e.toString()}");
    });

    ///Step: 2
    initStoreInfo();
    super.initState();
  }

We’ll begin by examining how to obtain product data from product IDs. That is what our initStoreInfo function accomplishes.

Future<void> initStoreInfo() async {
    final bool isAvailable = await _inAppPurchase.isAvailable();
    if (!isAvailable) {
      setState(() {
        _isAvailable = isAvailable;
        _products = <ProductDetails>[];
        _notFoundIds = <String>[];
        _loading = false;
      });
      return;
    }

    Set<String> _subcriptionProductIds = <String>{
      sub1Id,
      sub2Id,
    };

    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate());
    }

    final ProductDetailsResponse productDetailResponse =
        await _inAppPurchase.queryProductDetails(_subcriptionProductIds);
    if (productDetailResponse.error != null) {
      setState(() {
        _queryProductError = productDetailResponse.error!.message;
        _isAvailable = isAvailable;
        _products = productDetailResponse.productDetails;
        _notFoundIds = productDetailResponse.notFoundIDs;
        print('_notFoundIds :: ${_notFoundIds.toList()}');
        _loading = false;
      });
      return;
    }

    if (productDetailResponse.productDetails.isEmpty) {
      setState(() {
        _queryProductError = null;
        _isAvailable = isAvailable;
        _products = productDetailResponse.productDetails;
        _notFoundIds = productDetailResponse.notFoundIDs;
        print('_notFoundIds : ${_notFoundIds.toList()}');
        print('productDetailResponse error :: ${productDetailResponse.error}');
        _loading = false;
      });
      return;
    } else {
      print('=====}');
    }

    setState(() {
      _isAvailable = isAvailable;
      _products = productDetailResponse.productDetails;
      _notFoundIds = productDetailResponse.notFoundIDs;
      print('No Products :: ${_notFoundIds.toList()}');
      _purchasePending = false;
      _loading = false;
    });
  }

Simply make the application public! In-app purchases will not be available until the app has been launched. Saving in a drought is impossible. You can choose to publish in alpha or beta. Go to your Play Store dashboard and select the Publish option. After two days, return to this blog.

After you’ve published your app, you’ll notice that your _products or ProductDetails object contains information such as the Id, title, description, and price.

The pricing is automatically translated to the local currency. Simply use your app’s price field to display internationalized pricing. Finally, we’ll put the _listenToPurchaseUpdated function into action.

_listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) async {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        ///Step: 1, case:1
        showPendingUI();
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          ///Step: 1, case:2
          handleError(purchaseDetails.error!);
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          ///Step: 1, case:3
          verifyAndDeliverProduct(purchaseDetails);
        }
        if (purchaseDetails.pendingCompletePurchase) {
          await _inAppPurchase.completePurchase(purchaseDetails);
        }
      }
    }
  }

You can use the PurchaseDetails object in your product delivery logic. It includes the following useful parameters.

purchaseID: The unique identifier of the purchase.

productID: The product ID of the purchase.

transactionDate: The transaction’s millisecond timestamp.

You can now begin the purchasing process by calling a simple function. In this case, I bought the first item in the _products array. You can use your own logic to decide which items to buy.

onTap: () {
     late PurchaseParam purchaseParam;
     final GooglePlayPurchaseDetails? oldSubscription =
           _getOldSubscription(productDetails, purchases);
         PurchaseParam = GooglePlayPurchaseParam(
                productDetails: productDetails,
                changeSubscriptionParam: (oldSubscription != null)
                ? ChangeSubscriptionParam(
                oldPurchaseDetails: oldSubscription,
                prorationMode: ProrationMode
                .immediateWithTimeProration,
          )
             null);
 },

So we finally completed it.

All you have to do now is call the initConnection method when your app launches. Bring all of the items from PaymentService into the UI and display your products. When a user selects a product and clicks the buy button, the buyProduct() method is invoked with the product in question. To handle all scenarios, listen to the _proStatusChangedListeners and _errorListeners.

Flutter In-App Purchase Output

Flutter In-App Purchase

The source code for the this in-app purchase App integrated with in-app-purchase can be found on GitHub.

https://github.com/Mitali8620/in_app_purchase_demo

Read these official blogs to learn more about In-App Purchases.

Android: Integrate the Google Play Billing Library into your app

Thank you for taking the time to read this. If you have any questions or comments about this article, please leave them below.

In the article, I explained the basic architecture of In-app purchase ; you can modify this code to suit your needs; and this was a brief introduction to In-app purchase from my end, with Flutter support.

I hope this blog has provided you with sufficient information to experiment with in-app in your flutter projects. Please try this demo programmer, which will integrate In-app in a flutter application.

Thank you …. Have a beautiful day 🙂🙂🙂🙂🙂

Even though this article cover the majority of what to do to get in-app purchases working, I highly recommend reading the official documentation of the package supplied by the flutter team at https://pub.dev/packages/in app purchase.

Recommended Article’s

Firebase In-App Messaging

Paypal Payment integration in flutter

RazorPay Payment in flutter