Home Blog Page 25

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

How to convert base64 string to file in NodeJS

0
convert base64 to file
convert base64 to file

Hi Guy’s Welcome to Proto Coders Point, In this Article let’s learn how to convert base64 string to file in NODEJS. This works for all kinds of file like Image File, Video File or any kind of document like text, pdf, word File etc.

Convert base64 string to file in nodejs

To convert base64 string to file we can make use of File System Module of NodeJS.

File System Module is an NodeJS library that lets you work with system file & perform read write operation with computer files.

Install fs in nodeJS project

npm i fs

import fs to use it

const fs = require('fs');

let’s assume you already have a file in base64 format.

var base64Str = "SGkgR3V5J3MgV2VsY29tZSB0byBQcm90byBDb2RlcnMgUG9pbnQs";

Convert base64 to file

use writeFile function from fs module to convert base64 to file in nodejs with desired file extension.

fs.writeFile("fileName.txt",base64Str,{encoding:'base64'},(error)=>{
        if(error){
            console.log("Error");
        }else{
            console.log("File Created");
        }
});

Complete Code base64 to file in node

const fs = require('fs');
var base64Str = "SGkgR3V5J3MgV2VsY29tZSB0byBQcm90byBDb2RlcnMgUG9pbnQs"

fs.writeFile("fileName.txt",base64Str,{encoding:'base64'},(error)=>{
        if(error){
            console.log("Error");
        }else{
            console.log("File Created");
        }
});
convert base64 to file in nodejs
convert base64 to file in nodejs

What is runApp() function in flutter

0
runapp in flutter
runapp in flutter

In Flutter, The runApp() function is used to initialize the application and start it. It’s basically a starting point on any flutter application, The runApp(<arg>) as an argument it accept a widget, which is the top-level widget that will be used as the root of the app’s widget tree. This runApp in flutter is should be called in main() function of flutter code and it will kick off the process and render the UI of flutter app on the user screen.

If you have a root-level widget called MyApp, you can run the flutter app using the following code:

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

Typically runApp() function is called within main() function of flutter app, As I said above it’s an staring point of any flutter app execution. You can say it as entry point of app, it is the first method that execute when user start your flutter app.

Complete Example on flutter runApp()

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: Scaffold(
        body: Center(
          child: Text('Hello World'),
        ),
      ),
    );
  }
}

In Above Example, MyApp is the root widget passed to runApp(), which initializes and runs the Flutter app.

Basically runApp is responsible to create the WidgetsFlutterBinding that binds the framework and the flutter engine together, and is also responsible of creating RendererBinding object, whose task is to render the given widget on user screen.

SOLID Principal in dart – flutter

0
S.O.L.I.D Principle in Dart Flutter
S.O.L.I.D Principle in Dart Flutter

Hello, dart and flutter developers! Today’s topic is SOLID principles in Dart. This is not about adding new language features; rather, it is about improving code quality and maintainability. These best practices are intended to be used in any object-oriented language, not just Dart.

Dart SOLID

What are the fundamental principles of Flutter?

The acronym SOLID stands for five well-known design principles:

  • Single Responsibility.
  • Open-Closed.
  • Liskov Substitution.
  • Interface Segregation.
  • and Dependency Inversion.

All of which will be discussed further below. They are very popular among developers and are widely accepted as good practices.

What issue did these S.O.L.I.D principles solve?

  •  Jumping multiple methods with the same name and spending a significant amount of time to fix a minor bug.
  • Rereading the code several times to find the section that needs to be changed.

It’s difficult to understand what the method does.

Essentially, we spend far more time understanding than we do writing code.


SOLID Principal in dart – flutter

Single Responsibility principle

This principle states that a class should only change for one reason. In other words, you should design classes with a single “responsibility” to make them easier to maintain and more difficult to break.

As the name implies, it is solely responsible. A class should only be responsible for one thing, which means it should only change for one reason.

Let’s start with a bad practice in which maintenance is unpleasant. Because everything is in one place: validation, getRequest, and painting.

class Shapes {
  List < String > cache = List < > ();

  // Calculations
  double squareArea(double l) {
    /* ... */ }
  double circleArea(double r) {
    /* ... */ }
  double triangleArea(double b, double h) {
    /* ... */ }

  // Paint to the screen
  void paintSquare(Canvas c) {
    /* ... */ }
  void paintCircle(Canvas c) {
    /* ... */ }
  void paintTriangle(Canvas c) {
    /* ... */ }

  // GET requests
  String wikiArticle(String figure) {
    /* ... */ }
  void _cacheElements(String text) {
    /* ... */ }
}

Because it handles internet requests, work, and calculations all in one place, This class completely destroys the SRP. This class will change frequently in the future: whenever a method requires maintenance, you’ll have to change some code, which may break other parts of the class. What do you think about this?

// Calculations and logic
abstract class Shape {
  double area();
}

class Square extends Shape {}
class Circle extends Shape {}
class Rectangle extends Shape {}

// UI painting
class ShapePainter {
  void paintSquare(Canvas c) {
    /* ... */ }
  void paintCircle(Canvas c) {
    /* ... */ }
  void paintTriangle(Canvas c) {
    /* ... */ }
}

// Networking
class ShapesOnline {
  String wikiArticle(String figure) {
    /* ... */ }
  void _cacheElements(String text) {
    /* ... */ }
}

Open-Closed Principle

You should be able to extend the behavior of a (class, module, function, etc.) without modifying it.

According to the open-closed principle, a good programmer should add new behaviors without changing the existing source code. This concept is notoriously described as “classes should be open for extension and closed for changes”.

// Looks good but wait! Customer wants a revision in the last second and wants a third number to add. How we can solve this problem without breaking the app?int sum(int a, int b) {
int sum(int a, int b) {
  return a + b;
}

// Breaks old functionality
int sum(int a, int b, int c) {
  return a + b + c;
}

// There is no problem for old codes because this one wont be affected by new codes
int sum(int a, int b, [int c = 0]) {
  return a + b + c;
}


Liskov Substitution Principle

This principle suggests that “parent classes should be easily substituted with their child classes without blowing up the application”. To explain this, consider the following example.

The architecture ensures that the subclass maintains the logic correctness of the code. Composition with interfaces is preferred over inheritance.

abstract class StorageService {
  void get(String key);
  void put(String key, String value);
}

class HiveService implements StorageService {
  @override
  void get(String path) {}

  @override
  void put(String key, String value) {}
}

class ObjectBoxService implements StorageService {
  @override
  void get(String key) {}

  @override
  void put(String key, String value) {}
}

Interface Segregation Principle

This principle suggests that “many client specific interfaces are better than one general interface“. This is the first principle that applies to an interface; the other three principles apply to classes.

abstract class Teacher{
  void work();
  void sleep();
}

class Human implements Teacher{
  void work() => print("I do a lot of work");
  void sleep() => print("I need 10 hours per night...");
}

class Robot implements Teacher{
  void work() => print("I always work");
  void sleep() {} // ??
}

The issue here is that robots do not require sleep, so we are unsure how to implement that method. Worker represents an entity capable of performing work, and it is assumed that if you can work, you can also sleep. In our case, this assumption is not always correct, so we’ll divide the class:

abstract class Teacher{
  void work();
}

abstract class Sleeper {
  void sleep();
}

class Human implements Teacher, Sleeper {
  void work() => print("I do a lot of work");
  void sleep() => print("I need 10 hours per night...");
}

class Robot implements Teacher{
  void work() => print("I'm always iiii work as teacher");
}

Dependency Inversion Principle (DIP)

The issue here is that robots do not require sleep, so we are unsure how to implement that method. Worker represents an entity capable of performing work, and it is assumed that if you can work, you can also sleep. In our case, this assumption is not always correct, so we’ll divide the class:

Assume we have a Firebase-integrated app and want to migrate the database to a PhpDataBaseserver later. If we make them rely on an interface, there will be no problem; all we need to do is change the service.

As if you were changing the batteries in a toy. The toy is still an old toy, but the batteries are new.

abstract class DataApi {
  Future get(String path);
}

class FirebaseService implements DataApi {
  @override
  Future get(String path) async {
    return await Future.value('Data from Firebase');
  }
}

class PhpDBService implements DataApi {
  @override
  Future get(String path) async {
    return await Future.value('Data from PhpDBService ');
  }
}

Instead of use

abstract class DataService {
  FutureOr<String> fetch();
}
class FirebaseService extends DataService {
  @override
  Future<String> fetch() async => await 'data';
}
class LocaDataService extends DataService {
  @override
  String fetch() => 'data';
}

Conclusion

Avoid being trapped by Solid.

S.O.L.I.D. Principles are not rules, but rather principles.

When using this, always use common sense. Your goal is to make your code maintainable and easy to extend.

Avoid fragmenting your code excessively for the sake of SRP or S.O.L.I.D.

Thank you for reading the SOLID principles ….Have a fine day!!

Flutter Redux – A state Management in flutter

0

We’ll concentrate on the Flutter app and utilise Redux to control its state. Redux is an architecture for unidirectional data flow that makes it simple to create, manage, and test apps.

Redux is one of the various state management approaches in Flutter. Redux, in general, is a unidirectional data flow architecture that makes it simple for developers to create and maintain apps.

What is Redux in Flutter?

Data is repetitively distributed between widgets with success using Redux, a state management architectural framework. Through the use of a unidirectional data flow, it controls the state of an application. Let’s examine the illustration below:

Here are the four elements that Redux often contains. Redux is ingeniously created so that the user can simply interact with the App, which involves frequent state changes.

i) Action: When an event is created, it is subsequently dispatched to the Reducer as an action.

ii) Reducer: Reducer refreshes the store with the new state it receives whenever it receives an update.

iii) Store: The Store notifies the View of any updates it gets.

iv) View: To demonstrate the changes that have been done, it has been reconstructed.

Redux Middleware is the primary component that is essential to the process described above, thus the question arises: what is middleware and what does it do?

So first we’ll discuss about…

What is middleware ??

Every action that is submitted to the reducer can be intercepted using Redux Middleware, allowing you to adjust or stop the action.

You may make asynchronous requests, report errors, and much more with the aid of middleware.

Before your app sends a response back to the server or even within the app itself, middleware plays a crucial function. Depending on the situation, we can utilize middleware to lead the user to a different page or screen.

Application middleware manages data when it is dispatched from the action and before it reaches the reducer while doing any operation, such as fetching any data from a third-party API.

When it comes to Redux’s operation, there are typically two alternative methods that any Basic App can use

1) When every state is kept in one store:

Developers can access the Stored States, which contain all the data updates they require, when all the states are kept in a single store. If a state has to be updated, the app will be notified.

2 ) When information is unidirectional:

Data flow is unidirectional, making it easier to handle data and carry out the procedure that entails the four steps that were previously discussed.

What is the significance of state management?

State management is crucial for Flutter app development since it enables us to centralise all UI states and manage data flow.

When a child widget requires data in a medium or large-scale application with many widgets, it is common to manage the data from the main.dart file.

This data could be distributed as arguments through widget constructors until it reaches the recipient widget, but as we discussed in the introduction, this could result in a long chain of data transfer through widgets that don’t need this data.

It is not only inconvenient and difficult to pass data through constructors, but it can also have an impact on application performance. This is due to the fact that when you manage data from the main widget — or any root widget — the entire widget tree rebuilds whenever any of its child widgets changes. Only the build method in the widget that requires the changed data should be called.

It refers to controlling the state of one or more user interface control systems, such as radio controls, action buttons, input fields, and so on. It is a User Interface programming technique in which the state of a single UI control is completely or partially dependent on the state of all the other UI controls.

Can Redux be used with Flutter?

The store, which will be used to establish the initial state of the store, is one of the key tools needed to utilize Redux in Flutter apps.

The architecture of Flutter Redux

Store

An object that contains the application’s state. This object can be found in the project’s files with the help of the provider. The only way to change its state is to perform an action on it. 

There are three important parts of the store:

  • createStore(): To create a store object in redux.
  • dispatch(action): To change the state of store data by using the actions.
  • getState(): For getting the current state of the store in redux.

Flutter manipulates the store using inherited widgets. Among the inherited widgets are:

StoreProvider: This widget injects the store into the application’s widget tree.

class MyApp extends StatelessWidget {

 @override
 Widget build(BuildContext context) {

     ...

   return StoreProvider<AppState>(
     store: store,
     child: MaterialApp(
       title: 'Flutter Redux app’,
       theme: ThemeData.dark(),
       home: StoreBuilder<AppState>(
        ...// do here
       ),

     ),
   );
 }
}

StoreBuilder: listens to the entire store and rebuilds the entire widget tree with each update; it receives the store from StoreProvider and StoreConnector.

@override
 Widget build(BuildContext context) {

  ...

   return StoreProvider<AppState>(
     store: store,
     child: MaterialApp(
       title: 'Flutter Redux app,
       theme: ThemeData.dark(),
       home: StoreBuilder<AppState>(
           onInit: (store) => store.dispatch(Action()),
         builder: (BuildContext context, Store<AppState> store) => MyHomePage(store),
       ),

     ),
   );
 }

StoreConnector: a widget that replaces the StoreBuilder. It gets the store from StoreProvider, reads data from our store, and then passes it to its builder function. When that data changes, the builder function rebuilds the widget.

class HomePage extends StatelessWidget{
 final Store<AppState> store;

 MyHomePage(this.store);

 @override
 Widget build(BuildContext context){

   return Scaffold(
     appBar: AppBar(
       title: Text('Redux '),
     ),
     body: StoreConnector<AppState, Model>(
       builder: (BuildContext context, Model model) {
   ...
  }
 }
}

This is the central location where the application state can be found. At any given time, the store contains information about the entire application state or any other, single state.

final Store<AppState> store = Store<AppState>(
reducer, initialState: AppState.initialState()
);

What exactly are Redux actions?

Actions are objects with a type and a payload that can be specified. The type describes the action’s intent, and the payload is the data that goes with it. Sometimes the type of the action is all that is required to transfer the state, in which case the action does not require a payload.

Following the event on this state, the widgets that are tracking the data in the state rebuild, and the data they render is updated to the state’s current values. Any event sent to the store to update the app’s state is considered an action.

final Store<AppState> store = Store<AppState>(
reducer, initialState: AppState.initialState()
);

store.dispatch(Action());

When a widget wants to change the state with an action, it uses the store’s dispatch method to notify the state of the action — the store invokes the action.

Reducers

The root reducer combines all of the reducers that construct various pieces of state.Reducer is a function that adds a new state to the store. It takes as arguments the state and the action and updates the state based on the action. Remember that the state is immutable and can only be changed by creating a new state. The only way to update the state is through the reducer.

Assume a pop-up appears on the screen and a user response is required in the form of clicking or tapping a button. In our diagram above, we’ll refer to this pop-up as the View.

The Action is the result of clicking the button. This action is wrapped and sent to the Reducer, which processes it and updates the Store data. The store then holds the application’s State, and the state detects the change in data value.

Because the state manages the data rendered on your screen, any change in data is reflected in the View, and the cycle continues.

Redux In Flutter’s goal

Why use Redux when we can utilise straightforward classes and widgets is a common topic?

When building an E-Commerce project in Flutter, the Cart Screen will display the cart’s contents. From other screens where the Cart is shown, we may add, edit, and remove the goods. Redux was required to manage the logic and UI for adding, updating, and deleting items from the Cart since we had to update the Cart screen after any sort of action. Redux is employed in this.

The MVP pattern and managing a View’s state via RX Observables are similar Android design concepts.

Implementation

How to implement Redux in Flutter?

Step 1) : Install the Packages:

Add the pubspec.yaml file in dependencies.

Dependencies:

flutter_redux:
redux:

Step 2) : Run flutter packages get in the root directory of your app.

Step 3) : Import the file

import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';

We next move on to the redux implementation phase, thus first.

Redux : includes and offers the basic tools necessary for Redux to be used in Flutter applications, including:

  •  The shop that will be used to specify the store’s starting state
  • Reducer functionality
  • using middleware

Flutter_redux: This adds an extra collection of utility widgets in addition to the Redux package, such as:

  • StoreProvider
  • StoreBuilder 
  • StoreConnector

Flutter_redux_dev_tools: When compared to the Flutter Redux package, the flutter redux dev tools package offers more tools for tracking changes to the state and actions taken.

redux thunk: in order to introduce middleware

http: makes it possible to use middleware to call an external API.

After experimenting with various architectures, I decided to combine Flutter with Redux because it is both challenging and enjoyable. I chose a simple and common case to document the development and share this experience with you: the Welcome — Sign-In — Sign-Up flow.

There are two major requirements:

The Flux pattern and the Redux framework are theoretically understood. You should understand Store and why it is the Single Source of Truth, Reducers and why they are Vanilla functions, and so on.

A fundamental understanding of the redux and flutter redux plugins used by the Flutter framework to implement the Redux architecture.

Example

Add this in main.dart file

  @override
  Widget build(BuildContext context) {
    return StoreProvider<int>(
      store: store,
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData.light(),
        title: "Redux App",
        home: const MyHomeScreen(),
      ),
    );
  }

Create the dart file name with HomePage and add this code

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("How to use Redux")),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            StoreConnector<int, String>(
              converter: (store) => store.state.toString(),
              builder: (context, count) {
                return Text(
                  count,
                  style: const TextStyle(fontSize: 20),
                );
              },
            ),
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                StoreConnector<int, VoidCallback>(
                  converter: (store) {
                    return () => store.dispatch(ReducerAction.Increment);
                  },
                  builder: (context, callback) {
                    return TextButton(
                      onPressed: callback,
                      child: const Icon(Icons.add),
                    );
                  },
                ),
                StoreConnector<int, VoidCallback>(
                  converter: (store) {
                    return () => store.dispatch(ReducerAction.Decrement);
                  },
                  builder: (context, callback) {
                    return TextButton(
                      onPressed: callback,
                      child: const Icon(Icons.remove),
                    );
                  },
                )
              ],
            )
          ],
        ),
      ),
    );
  }

Flutter Bloc vs. Flutter Redux

  • Redux employs a global store, which allows for the representation of your whole application state in a single state.
  • The application state is split into several blocs by the bloc.
  • The Business Logic Component is referred to as Bloc.
  • For the Flutter Bloc, you don’t need to write reducers, actions, etc.

Code link 👍

https://github.com/kevalv001/flutter_redux_example.git

Conclusion 

In the article, I have explained the basic architecture of Redux state management , you can modify this code according to your choice, and this was a small introduction of Redux from my side and its working using Flutter.

If you like this article, then do not forget to give your likes & claps! 🙂

Thank you!!!!!!! Have a happy day !!

Frontend Interview Question with Answer

0
Frontend Interview Question with Answer-min

1. What are meta tags in HTML?

  • Meta Tags are those tags that go inside the head tag of HTML page.
  • Meta Tags are not for the user interface but are important for a browser.
  • Meta Tags are always in name: value pair.
  • Meta tags typically include character encoding, a title, and a description.

2. What is load balancing?

Load balancing involves distributing of incoming network traffic evenly across backend servers to optimize performance and minimize response time. In order to enhance performance and reduce response time, load balancing is a technique used to spread workloads equitably across numerous servers or devices.

3. What is the scope of JavaScript?

In JavaScript, a function’s scope defines the rules for accessing variables and the variables themselves. Every function has its own unique scope.

4. what is Content Security Policy?

Content security Policy is also known as CSP is a header in HTML that lets the site operators gain the whole control over the resources which are loading on the site. CSP Helps to prevent cross-site scripting (XSS) attacks and other types of injection attacks. When a web page is requested, the server sends the client an HTTP header that is implemented as a CSP.

5. How are JavaScript and jQuery different?

JQuery is a library written in JavaScript, which is the programming language it is based on. In comparison to jQuery, which is a library that provides a set of tools and conveniences for dealing with JavaScript, JavaScript is a programming language that can be used to create web apps. JavaScript can be used without jQuery, but jQuery needs JavaScript to function.

6. What is Cross-Site Scripting (XSS)?

Cross-Site Scripting (XSS) is an attack in which an attacker injects malicious code, in the form of browser-side script, into a web application and sends it to another user.

7. What npm stands for?

Npm stands for Node Package Manager, is a package manager for the JavaScript programming language(NodeJS). npm is basically used to install and manage packages (libraries, frameworks, tools, etc.).

8. What is User Centered Design?

User-centered design is a design process that focuses on meeting the needs of users and considering their perspective in every phase of design.

9. What is a grid system in CSS?

The grid system is a layout structure that allows content to be organized horizontally and vertically in a consistent and organized manner. It consists of rows and columns, which are the two key components of the grid.

10. What is Mixin?

A CA Mixin is a group of CSS declarations that can be reused throughout a website to simplify the styling process.