Home Blog Page 15

How to Clear Cache of Computer

0
How to Clear Cache of Computer

Hi Guy’s, When you purchase a new Computer or Laptop it works very smooth at the beginning but after using it for say 6 month or 1 year, you start noticed that your computer/PC/Laptop is not running slow & you are experiencing lag/glitches, That’s because the cache memory is full and there is no storage left to store more cache and now it’s time to clear the cache of the computer.

What is Computer Cache Memory?

The cache is one of the temporary storage location that is been used to store frequently used data/application which will improve the performance of your computer. However, over time, At sometime in future the cache data been stored become cluttered with unnecessary files or may be old cache data been stored which is not automatically cleared, thus this will leading to a decrease in speed and performance. By Clearing the cache will help you in optimize your computer’s performance and clear the cache storage space. In this article, We are here to help you on the step by step method on how to clear cache of a computer.

Step 1: Clearing all the Browser Cache

The browser that you make use for you daily browsing has it’s own cache stores temporary files space like for example once you visit a website, the date such as images, scripts, html data and website data is been stored in to browser cache memory so that when you revisit the same website you get website loading experience. and thus your browser will also has cache data that us unnecessary and need to be cleared. Here’s How to clear the cache in popular web browsers:

  • Google Chrome: On the Top-Right corner you will see three-dot click on it, go to "More tools,"& select "Clear browsing data." Choose the time range, then you get option on which type of data you want to clear like Browsing history, Cookie, Cache Images and files and more select one or all of then, and simply click on "Clear data."
  • Mozilla Firefox: On Top-Right corner you will see a menu button(3 line icon button) click on it to open menu, go to "Settings” and then select "Privacy & Security." from the sidebar menu then Scroll down you will see a section called "Cookies and Site Data" and click on "Clear Data." Now Check the box that says "Cached Web Content" & click on "Clear." button.
  • Safari: In Safari Browser, navigate to Safari menu, & select "Preferences," from the menu list & click on the "Privacy" tab. Nopw Click on “Manage Website Data” and then finally “Remove All” that will clear all the cache of safari browser.

Step 2: Clearing the System Cache

As we discussed what is cache memory and what is the use of it. We saw in step 1 how to clear browser cache, In this step 2 will be check how to clear computer cache.

To clear Cache in Windows Computer all you need to do it delete temperary files to do so follow below steps:

  • Press the Windows key + R, This will open a Run dialog box. Now type “temp” and press Enter. This will quickly open the directory where all your temporary files & folder are stored. Select all files and folders inside the folder (ctrl + A) and Delete them.
  • Press the Windows key + R again and this time type “%temp%” to open the temporary files folder for your user account. Delete all files and folders inside.
  • Finally, the last step is to delete files from prefetch folder to do so, Press the Windows key + R, open the Run dialog box once more and type “prefetch.” Delete all files in the Prefetch folder.

Clearning System Cache on Mac OS – How to clear cache of mac

On a Mac, clearing the cache involves a few different steps:

  • Open Finder and click on “Go” in the menu bar. Select "Go to Folder" and type "~/Library/Caches." Delete the contents of the Caches folder.
  • Next, go back to the “Go” menu and select "Go to Folder" again. This time, type "/Library/Caches" and delete the contents of this folder as well.

Step 3: Restart Your Computer

It’s a good practice to always restart the computer once the cache is been cleared, so that all the changed get effected and your computer be get fresh.

No need to Regularly clear the cache of your computer but you can do it once in 10 days for you PC to maintain and its performance.

GIT Commands that every software developer should know

0
Git Commands
Git Commands.

In the Software Development world version control plays an very important role in securing you project source code by mentaining a proper version of your project, As said Git commands are the backbone through which one can manage and track changes in software development projects and each developer is given a git branch when he and upload and keep backup of his code and maintain version.

In this git article, let’s dive into the all the essential GIT commands that every software developer should know, that empower developer to easily manage version control.

Git Commands

git init

This git command is basically used to start a new git repository. it will create a .git file in project directory.

 git init [repository name]

git clone

This git command is used to clone or download a repository from an existing gitHub repo.

git clone [repository URL]

git add [file name]

This git command is used to stage or add a file what will be pushed into github repo using git push cmd.

 git add [file name]

git add .

This git command is used to add all file what will be pushed into github repo using git push cmd.

git add .

git commit – m

This git command takes a snapshot of project’s currently staged changes.

git commit -m “[ meaningful message]”

git diff

This command shows the file differences which are not yet staged.

git diff

git diff -staged

This command shows the differences between files in the staging area and latest version present.

git diff -staged

git status

This command shows all the modified files which are not committed.

git status

git log

This command shows the list of version history.

git log

git branch

This command shows all the branches of repo.

git branch

git checkout

This command is used to switch between branches.

git checkout [branch name]

To create new branch and switch to that.

git checkout -b [branch name]

git push

This command sends all committed changes to your repo.

git push origin master

git merge

This command shows all the branches of repo.

git merge [branch name]

git pull

This command fetch and merge changes.

git pull [Repository Link]

git stash

This command temporarily stores all the modified tracked files.

git stash save

How to Customize Razorpay UI in Flutter using Package

0
razorpay in flutter
razorpay UI in flutter

The only provider of converged payments solutions in India that offers a product suite that enables your company to accept, process, and disburse payments is Razorpay. You can use all payment methods, including credit and debit cards, UPI and well-known mobile wallets with Razorpay.

Flutter Razorpay’s Custom-UI

Flutter plugin for the Razorpay Custom SDK. This flutter plugin is wrapper for our SDKs for Android and iOS both.

To learn more about this SDKs, how you can integrate them into flutter projects refer to this documentation :

Become familiar with the Razorpay Payment Flow.

Create a Razorpay Account and then use the Razorpay Dashboard to generate the API Keys. The Test keys can be used to mimic a sandbox environment. When using the Test keys, no genuine financial transaction takes place. Once the application has undergone extensive testing and is ready to go live, use Live keys.

Integrating Razorpay with custom UI in flutter app

Get started…

Installation

Step 1: Add this following dependencies into flutter project in pubspec.yaml file :

razorpay_flutter_customui: ^any

Step 2: Then to download the packahge use the terminal’s command line:

flutter pub get

Step 3: Import the dart file where required:

import 'package:razorpay_flutter_customui_example/payment_slection_page.dart';

Step 4: Make an instance of Razorpay.

_razorpay = Razorpay();

Event Listeners:

The event of a successful or unsuccessful payment is released by this plugin which employs event-based communication.

The event names are revealed using the Razorpay class constants EVENT PAYMENT SUCCESS, EVENT PAYMENT ERROR and EVENT EXTERNAL WALLET.

EVENT PAYMENT SUCCESS – for Successful payment

EVENT PAYMENT ERROR – for Error while payment is recorded

EVENT EXTERNAL WALLET – for The external wallet that was used for payment

Within the Razorpay class these occurrences are categorised as constants. The following code shows how to manage events by defining listener methods for each individual event:

 _razorpay?.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
 _razorpay?.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
 _razorpay?.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);

Razorpay method

void _handlePaymentSuccess(PaymentSuccessResponse response) {
  // when payment succeeds
}
void _handlePaymentError(PaymentFailureResponse response) {
  // when payment fails
}
void _handleExternalWallet(ExternalWalletResponse response) {
  // when an external wallet was selected
}
//for clear the listener
 _razorpay.clear();

Create a function called openChecF() that accepts the API key, order id, amount, name and description in order to open the payment interface. The options variable which is supplied to the razorpay. open function contains these parameters.

void openChec() async {
    var options = {
      'key': 'Your_RazorPay_Key',
      'amount': 200,
      'name': 'jhon',
      'description': 'Payment',
      'prefill': {'contact': '9999999999', 'email': 'jhon@razorpay.com'},
      'external': {
        'wallets': ['paytm']
      }
    };

    try {
      _razorpay?.open(options);
    } catch (e) {
      debugPrint(e.toString());
    }
  }

Add this code you root directory file and follow this 

RazorPay UI Example

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:razorpay_flutter_customui/razorpay_flutter_customui.dart';
import 'model/card_info_model.dart';

enum PaymentMethods { card, upi, nb, wallet, vas }

class PaymentSelectionPage extends StatefulWidget {
  @override
  _PaymentSelectionPageState createState() => _PaymentSelectionPageState();
}

class _PaymentSelectionPageState extends State<PaymentSelectionPage> {
  String selectedPaymentType = 'CARD';
  PaymentMethods selectedMethod = PaymentMethods.card;
  CardInfoModel? cardInfoModel;
  String key = "rzp_test_1DP5mmOlF5G5ag";
  String? availableUpiApps;
  bool showUpiApps = false;

  //rzp_test_1DP5mmOlF5G5ag  ---> Debug Key
  //rzp_live_6KzMg861N1GUS8  ---> Live Key
  //rzp_live_cepk1crIu9VkJU  ---> Pay with Cred

  Map<String, dynamic>? netBankingOptions;
  Map<String, dynamic>? walletOptions;
  String? upiNumber;

  Map<dynamic, dynamic>? paymentMethods;
  List<NetBankingModel>? netBankingList;
  List<WalletModel>? walletsList;
  late Razorpay _razorpay;
  Map<String, dynamic>? commonPaymentOptions;

  @override
  void initState() {
    cardInfoModel = CardInfoModel();
    _razorpay = Razorpay();
    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
    _razorpay.initilizeSDK(key);
    fetchAllPaymentMethods();

    netBankingOptions = {
      'key': key,
      'amount': 100,
      'currency': 'INR',
      'email': 'ramprasad179@gmail.com',
      'contact': '9663976539',
      'method': 'netbanking',
    };

    walletOptions = {
      'key': key,
      'amount': 100,
      'currency': 'INR',
      'email': 'ramprasad179@gmail.com',
      'contact': '9663976539',
      'method': 'wallet',
    };

    commonPaymentOptions = {};

    super.initState();
  }

  fetchAllPaymentMethods() {
    _razorpay.getPaymentMethods().then((value) {
      paymentMethods = value;
      configureNetBanking();
      configurePaymentWallets();
    }).onError((error, stackTrace) {
      print('E :: $error');
    });
  }

  configureNetBanking() {
    netBankingList = [];
    final nbDict = paymentMethods?['netbanking'];
    nbDict.entries.forEach(
      (element) {
        netBankingList?.add(
          NetBankingModel(bankKey: element.key, bankName: element.value),
        );
      },
    );
  }

  configurePaymentWallets() {
    walletsList = [];
    final walletsDict = paymentMethods?['wallet'];
    walletsDict.entries.forEach(
      (element) {
        if (element.value == true) {
          walletsList?.add(
            WalletModel(walletName: element.key),
          );
        }
      },
    );
  }

  void _handlePaymentSuccess(Map<dynamic, dynamic> response) {
    final snackBar = SnackBar(
      content: Text(
        'Payment Success : ${response.toString()}',
      ),
      action: SnackBarAction(
        label: 'Okay',
        onPressed: () {},
      ),
    );
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
    print('Payment Success Response : $response');
  }

  void _handlePaymentError(Map<dynamic, dynamic> response) {
    final snackBar = SnackBar(
      content: Text(
        'Payment Error : ${response.toString()}',
      ),
      action: SnackBarAction(
        label: 'Okay',
        onPressed: () {},
      ),
    );
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
    print('Payment Error Response : $response');
  }

  String validateCardFields() {
    if ((cardInfoModel?.cardNumber == '') ||
        (cardInfoModel?.cardNumber == null)) {
      return 'Card Number Cannot be Empty';
    }
    if ((cardInfoModel?.expiryMonth == '') ||
        (cardInfoModel?.expiryMonth == null)) {
      return 'Expiry Month / Year Cannot be Empty';
    }
    if ((cardInfoModel?.cvv == '') || (cardInfoModel?.cvv == null)) {
      return 'CVV Cannot be Empty';
    }
    if ((cardInfoModel?.mobileNumber == '') ||
        (cardInfoModel?.mobileNumber == null)) {
      return 'Mobile number cannot be Empty';
    }
    if ((cardInfoModel?.email == '') || (cardInfoModel?.email == null)) {
      return 'Email cannot be Empty';
    }
    return '';
  }

  @override
  void dispose() {
    super.dispose();
    _razorpay.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Select Payment Method'),
      ),
      backgroundColor: Colors.blue.shade50,
      body: SafeArea(
        child: Container(
          color: Colors.white,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Align(
                  alignment: Alignment.center,
                  child: Wrap(
                    spacing: 8.0,
                    runSpacing: 8.0,
                    children: [
                      PaymentTypeSelectionButton(
                        paymentTitle: 'CARD',
                        onPaymentTypeTap: () {
                          setState(() {
                            selectedPaymentType = 'CARD';
                            selectedMethod = PaymentMethods.card;
                          });
                        },
                      ),
                      PaymentTypeSelectionButton(
                        paymentTitle: 'UPI',
                        onPaymentTypeTap: () {
                          setState(() {
                            selectedPaymentType = 'UPI';
                            selectedMethod = PaymentMethods.upi;
                          });
                        },
                      ),
                      PaymentTypeSelectionButton(
                        paymentTitle: 'NET BANKING',
                        onPaymentTypeTap: () {
                          setState(() {
                            selectedPaymentType = 'NET BANKING';
                            selectedMethod = PaymentMethods.nb;
                          });
                        },
                      ),
                      PaymentTypeSelectionButton(
                        paymentTitle: 'WALLET',
                        onPaymentTypeTap: () {
                          setState(() {
                            selectedPaymentType = 'WALLET';
                            selectedMethod = PaymentMethods.wallet;
                          });
                        },
                      ),
                      PaymentTypeSelectionButton(
                        paymentTitle: 'VAS',
                        onPaymentTypeTap: () {
                          setState(() {
                            selectedPaymentType = 'VAS';
                            selectedMethod = PaymentMethods.vas;
                          });
                        },
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 32.0),
                Expanded(
                  child: getReleventUI(),
                ),
                Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Text(
                    'Selected Payment Type : $selectedPaymentType',
                    style: const TextStyle(
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget getReleventUI() {
    switch (selectedMethod) {
      case PaymentMethods.card:
        return buildCardDetailsForm();
      case PaymentMethods.upi:
        return buildUPIForm();
      case PaymentMethods.nb:
        return buildBanksList();
      case PaymentMethods.wallet:
        return buildWalletsList();
      case PaymentMethods.vas:
        return buildForVas();
      default:
        return buildUPIForm();
    }
  }

  Widget buildForVas() {
    return Column(
      children: [
        ElevatedButton(
          onPressed: () {},
          child: const Text('Make Payment'),
          style: ElevatedButton.styleFrom(
            primary: Colors.blue.shade900,
          ),
        ),
        ElevatedButton(
          onPressed: () {},
          child: const Text('Make Payment With Data'),
          style: ElevatedButton.styleFrom(
            primary: Colors.blue.shade900,
          ),
        )
      ],
    );
  }

  Widget buildWalletsList() {
    return ListView.builder(
      itemCount: walletsList?.length,
      itemBuilder: (context, item) {
        return ListTile(
          title: Text(walletsList?[item].walletName ?? ''),
          trailing: const Icon(Icons.arrow_forward_ios),
          onTap: () {
            walletOptions?['wallet'] = walletsList?[item].walletName;
            if (walletOptions != null) {
              _razorpay.submit(walletOptions!);
            }
          },
        );
      },
    );
  }

  Widget buildBanksList() {
    return ListView.builder(
      itemCount: netBankingList?.length,
      itemBuilder: (context, item) {
        return ListTile(
          title: Text(netBankingList?[item].bankName ?? ''),
          trailing: const Icon(Icons.arrow_forward_ios),
          onTap: () {
            netBankingOptions?['bank'] = netBankingList?[item].bankKey;
            if (netBankingOptions != null) {
              _razorpay.submit(netBankingOptions!);
            }
          },
        );
      },
    );
  }

  Widget buildUPIForm() {
    upiNumber = '';
    return Container(
      height: 200.0,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Column(
            children: [
              Row(
                children: [
                  const Text('VAP :'),
                  const SizedBox(width: 8.0),
                  Flexible(
                    child: TextField(
                      textAlign: TextAlign.center,
                      decoration: const InputDecoration(
                        hintText: 'VPA',
                      ),
                      onChanged: (value) {
                        upiNumber = value;
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 16.0),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ElevatedButton(
                  onPressed: () {
                    FocusScope.of(context).unfocus();
                    var options = {
                           'key': 'Your_RazorPay_Key',
                            'amount': 200,
                             'name': 'jhon',
                              'description': 'Payment',
                             'prefill': {'contact': '9999999999', 'email': 'jhon@razorpay.com'},
                              'external': {
                                      'wallets': ['paytm']
                                 }
                    };
                    _razorpay.submit(options);
                  },
                  style: ElevatedButton.styleFrom(
                    primary: Colors.blue.shade900,
                  ),
                  child: const Text('Intent Flow')),
              ElevatedButton(
                  onPressed: () {
                    if ((upiNumber == null) || (upiNumber == '')) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('Plese Enter VPA'),
                        ),
                      );
                      return;
                    }

                    FocusScope.of(context).unfocus();
                    var options = {
                      'key': key,
                      'amount': 100,
                      'currency': 'INR',
                      'email': 'ramprasad179@gmail.com',
                      'contact': '9663976539',
                      'method': 'upi',
                      'vpa': upiNumber,
                      '_[flow]': 'collect',
                    };
                    _razorpay.submit(options);
                  },
                  style: ElevatedButton.styleFrom(
                    primary: Colors.blue.shade900,
                  ),
                  child: const Text('Collect Flow'))
            ],
          ),
          ElevatedButton(
            onPressed: () async {
              final upiApps = await _razorpay.getAppsWhichSupportUpi();
              availableUpiApps = upiApps.toString();
              setState(() {
                showUpiApps = true;
              });
              print(upiApps);
            },
            style: ElevatedButton.styleFrom(
              primary: Colors.blue.shade900,
            ),
            child: const Text('Get All UPI Supported Apps'),
          ),
          Visibility(
            visible: showUpiApps,
            child: Flexible(
              child: Text(availableUpiApps ?? ''),
            ),
          )
        ],
      ),
    );
  }

  Widget buildCardDetailsForm() {
    return Container(
      height: 200.0,
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Column(
              children: [
                Row(
                  children: [
                    const Text('Card Number :'),
                    const SizedBox(width: 8.0),
                    Flexible(
                      child: TextField(
                        textAlign: TextAlign.center,
                        decoration: const InputDecoration(
                          hintText: 'Card Number',
                        ),
                        onChanged: (newValue) =>
                            cardInfoModel?.cardNumber = newValue,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16.0),
                Row(
                  children: [
                    const Text('Expiry :'),
                    const SizedBox(width: 8.0),
                    Flexible(
                      child: TextField(
                          textAlign: TextAlign.center,
                          decoration: const InputDecoration(
                            hintText: '12/23',
                          ),
                          onChanged: (newValue) {
                            final month = newValue.split('/').first;
                            final year = newValue.split('/').last;
                            cardInfoModel?.expiryYear = year;
                            cardInfoModel?.expiryMonth = month;
                          }),
                    ),
                    const SizedBox(width: 8.0),
                    const Text('CVV'),
                    const SizedBox(width: 8.0),
                    Flexible(
                      child: TextField(
                        textAlign: TextAlign.center,
                        decoration: const InputDecoration(
                          hintText: '***',
                        ),
                        onChanged: (newValue) => cardInfoModel?.cvv = newValue,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16.0),
                Row(
                  children: [
                    const Text('Name :'),
                    const SizedBox(width: 8.0),
                    Flexible(
                      child: TextField(
                        textAlign: TextAlign.center,
                        decoration: const InputDecoration(
                          hintText: 'Card Holder Name',
                        ),
                        onChanged: (newValue) =>
                            cardInfoModel?.cardHolderName = newValue,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16.0),
                Row(
                  children: [
                    const Text('Phone :'),
                    const SizedBox(width: 8.0),
                    Flexible(
                      child: TextField(
                        textAlign: TextAlign.center,
                        decoration: const InputDecoration(
                          hintText: 'Mobile Number',
                        ),
                        onChanged: (newValue) =>
                            cardInfoModel?.mobileNumber = newValue,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16.0),
                Row(
                  children: [
                    const Text('Email :'),
                    const SizedBox(width: 8.0),
                    Flexible(
                      child: TextField(
                        textAlign: TextAlign.center,
                        decoration: const InputDecoration(
                          hintText: 'Email-ID',
                        ),
                        onChanged: (newValue) =>
                            cardInfoModel?.email = newValue,
                      ),
                    ),
                  ],
                ),
              ],
            ),
            const SizedBox(height: 16.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ElevatedButton(
                  onPressed: () {
                    var error = validateCardFields();
                    if (error != '') {
                      print(error);
                      ScaffoldMessenger.of(context)
                          .showSnackBar(SnackBar(content: Text(error)));
                      return;
                    }
                    var options = {
                      'key': key,
                      'amount': 100,
                      "card[cvv]": cardInfoModel?.cvv,
                      "card[expiry_month]": cardInfoModel?.expiryMonth,
                      "card[expiry_year]": cardInfoModel?.expiryYear,
                      "card[name]": cardInfoModel?.cardHolderName,
                      "card[number]": cardInfoModel?.cardNumber,
                      "contact": cardInfoModel?.mobileNumber,
                      "currency": "INR",
                      'email': cardInfoModel?.email,
                      'description': 'Fine T-Shirt',
                      "method": "card"
                    };
                    _razorpay.submit(options);
                  },
                  style: ElevatedButton.styleFrom(
                    primary: Colors.blue.shade900,
                  ),
                  child: const Text('Submit'),
                ),
                ElevatedButton(
                    onPressed: () async {
                      /* print('Pay With Cred Tapped');
                      final paymentMethods = await _razorpay.getPaymentMethods();
                      print('Payment Methods Retrievend: $paymentMethods'); */

                      var options = {
                        'key': key,
                        'amount': 100,
                        'currency': 'INR',
                        'email': 'ramprasad179@gmail.com',
                        'app_present': 0,
                        'contact': '9663976539',
                        'method': 'app',
                        'provider': 'cred',
                        // 'callback_url': 'flutterCustomUI://'
                      };
                      // _razorpay.submit(options);
                      // String logo = await _razorpay.getBankLogoUrl("UTIB");
                      // print(logo);
                      /* final isvalidVpa = await _razorpay.isValidVpa('9663976539@upi');
                      print(isvalidVpa); */

                      /* final supportedUpiApps =
                          await _razorpay.getAppsWhichSupportUpi();
                      print(supportedUpiApps); */

                      /* final cardNetwork =
                          await _razorpay.getCardsNetwork("4111111111111111");
                      print(cardNetwork); */

                      /* final walletLogo
                          await _razorpay.getWalletLogoUrl('paytm');
                      print('Wallet URL : $walletLogo'); */

                      /* final length =
                          await _razorpay.getCardNetworkLength('VISA');
                      print(length); */
                    },
                    style: ElevatedButton.styleFrom(
                      primary: Colors.blue.shade900,
                    ),
                    child: const Text('Pay With Cred (Collect FLow)'))
              ],
            )
          ],
        ),
      ),
    );
  }
}

class PaymentTypeSelectionButton extends StatelessWidget {
  final String? paymentTitle;
  final VoidCallback? onPaymentTypeTap;

  PaymentTypeSelectionButton({
    this.paymentTitle,
    this.onPaymentTypeTap,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onPaymentTypeTap,
      child: Container(
        decoration:
            BoxDecoration(border: Border.all(color: Colors.black, width: 0.5)),
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(paymentTitle ?? ''),
        ),
      ),
    );
  }
}



For this example app source code click here GitHub

Video Tutorial on Integrating RazorPay in Flutter App

Conclusion

This is a small  flutter example that will integrate Razorpay custom ui ,  you can modify this code with your needs ,so just click on gitHub and get the code.

Thanks for reading this post 💙…..

Have a good day  

Dynamic cached fonts in Flutter

0
flutter dynamic cache fonts
flutter dynamic cache fonts

Dynamically cached fonts offer the ability to load and cache any font from any URL as needed. follow this technique helps reduce the bundle size of your application by allowing fonts to be loaded on-demand. By dynamically fetching fonts from external sources you can optimize your web performance and enhance user experience.

Because the font will only need to be downloaded once and used numerous times, caching improves performance while using less network and battery power.

How to Integrate Dynamic Cached Fonts in flutter app

To use the package, add dynamic_cached_fonts as a dependency.

Get started…

Installation.

Step 1): Add this following dependencies project pubspec.yaml file:

dynamic_cached_fonts: ^any

Step 2): Then import it after installing the package using the terminal’s command line:

flutter pub get

Step 3): import the file

import 'package:dynamic_cached_fonts/dynamic_cached_fonts.dart';

Loading the flutter dynamic cached fonts on page…

When a page loads, for instance, you can load a font on demand.

@override
void initState() {
  final DynamicCachedFonts dynamicCachedFont = DynamicCachedFonts(
    fontFamily: fontFamilyName, // The font family name to be passed to TextStyle.fontFamily
    url: fontUrl, // A valid url pointing to a font file (.ttf or .otf files only) 
  );
  dynamicCachedFont.load(); // Downloads the font, caches and loads it.

  super.initState();
}
...
Text(
  'Some Text',
  style: TextStyle(fontFamily: fontFamilyName),
)

Load the font , when button click

onPressed: () {
    final DynamicCachedFonts dynamicCachedFont = DynamicCachedFonts(
      fontFamily: fontFamilyName,
      url: fontUrl,
    );

    dynamicCachedFont.load();
  },

Pass in maxCacheObjects and cacheStalePeriod to alter the size of the cache or perhaps the length of time the font remains in cache.

DynamicCachedFonts(
  fontFamily: fontFamilyName,
  url: fontUrl,
  maxCacheObjects: 150,
  cacheStalePeriod: const Duration(days: 100),
);

TextStyle.fontOnly after load() is called are families applied.

What if you need to load several fonts, each with a different weight and style?The DynamicCachedFonts.family constructor can be used for that.

Incorporating a list of URLs directing users to various fonts within the same family enables the utilization of dynamically cached fonts. This approach allows for the dynamic loading and caching of fonts as required. By leveraging this functionality you can effectively reduce the overall size of your bundle while enabling the loading of fonts ondemand based on specific user needs. This approach enhances performance and optimizes user experience by seamlessly integrating range of fonts from different sources within cohesive font family.

DynamicCachedFonts.family(
  urls: <String>[
    fontFamilyNameBoldUrl,
    fontFamilyNameItalicUrl,
    fontFamilyNameRegularUrl,
    fontFamilyNameThinUrl,
  ],
  fontFamily: fontFamilyName,
);

Make use of the static methods if you require more control!

onPressed: () {
  DynamicCachedFonts.cacheFont(fontUrl);
},

The cacheStalePeriod and maxCacheObjects parameters are also available .

loadCachedFont , loadCached , canLoadFontFamily canTo see if the font is cached use the LoadFont method . It frequently works in tandem with the loadCached methods.

Before attempting to load a font, it is advisable to first check if the font is already cached . By verifying the font’s presence in the cache, you can avoid unnecessary network requests. If the font is indeed cached, you can proceed to activate it, ensuring a swift and seamless rendering of the font. This proactive approach optimizes the font loading process by efficiently utilizing the cached resources, resulting in improved performance and a smoother user experience.

if(DynamicCachedFonts.canLoadFont(fontUrl)) {
  // To load a single font...
  DynamicCachedFonts.loadCachedFont(
    fontUrl,
    fontFamily: fontFamilyName,
  );

  // Or if you want to load multiple fonts as a family...
  DynamicCachedFonts.loadCachedFamily(
    <String>[
      fontFamilyNameBoldUrl,
      fontFamilyNameItalicUrl,
      fontFamilyNameRegularUrl,
      fontFamilyNameThinUrl,
    ],
    fontFamily: fontFamilyName,
  );
}

Now, download the font if it isn’t already there in cache!

if(DynamicCachedFonts.canLoadFont(fontUrl)) {
 /// do code here
} else {
  DynamicCachedFonts.cacheFont(fontUrl);
}

RemoveCachedFont

To extend the functionality of RawDynamicCachedFonts and modify the implementation of static methods including the addition of removeCachedFont to permanently remove a font from the cache.

Do you want to load a specific font from Firebase Cloud Storage? Choose the constructor DynamicCachedFonts.fromFirebase! Google Cloud Storage locations with urls beginning with gs:// are accepted. It is similar to the default constructor aside from that.

This implementation file code is shown here;

import 'package:dynamic_cached_fonts/dynamic_cached_fonts.dart';
import 'package:flutter/material.dart';
import 'constants.dart';
import 'src/components.dart';
import 'src/demos.dart';

void main() {
  DynamicCachedFonts.toggleVerboseLogging(true);

  runApp(
    MaterialApp(
      title: 'Dynamic Cached Fonts Demo',
      home: const DynamicCachedFontsDemo1(),
      darkTheme: ThemeData.dark(),
    ),
  );
}

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

  @override
  _DynamicCachedFontsDemo1State createState() => _DynamicCachedFontsDemo1State();
}

class _DynamicCachedFontsDemo1State extends State<DynamicCachedFontsDemo1> {
  @override
  void initState() {
    final DynamicCachedFonts dynamicCachedFont = DynamicCachedFonts(
      fontFamily: cascadiaCode,
      url: cascadiaCodeUrl,
    );
    dynamicCachedFont.load();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(demoTitle),
      ),
      body: const Center(
        child: DisplayText(
          'The text is being displayed in $cascadiaCode which is being dynamically loaded and cached',
          fontFamily: cascadiaCode,
        ),
      ),
      floatingActionButton: ExtendedButton(
        icon: Icons.navigate_next,
        label: 'Next Example',
        onPressed: () => Navigator.push(
          context,
          MaterialPageRoute<DynamicCachedFontsDemo2>(
            builder: (_) => const DynamicCachedFontsDemo2(),
          ),
        ),
      ),
    );
  }
}

For this example code click here Github

Conclusion 👍

While the system fonts on Android and iOS are of a high caliber, designers frequently ask for custom fonts.This is a small example of dynamic cached fonts implemented in flutter , you can modify with your needs..

Thanks for reading this article 💙

Have a good day


Recommended Articles

Flutter Google Font’s Package

How to repair or clean cache of all dependencies in flutter

Icons in flutter – font awesome

Play YouTube Video in Flutter

0
flutter youtube video player
flutter youtube video player

Loading videos into flutter application youtube_player_flutter is one of the most popular packages that is been used to play youtube video into flutter app by development. Developers can easily play YouTube videos in their Flutter applications using the widget provided by this flutter package. The youtube_player_flutter package wraps the official YouTube Player API for Android and iOS, making it easy to integrate YouTube videos into your Flutter application.

Building useful user interfaces for mobile apps is made simple by Flutter’s selection of pre-built widgets and tools. Additionally, It has a feature called hot-reload that enables developers to view changes they make to their app immediately without having to restart it.

Introduction youtube_player_flutter

As I said to integrate youtube videos we will make use of flutter package, It is an easy-to-use straightforward package that provides a variety of video players with customizability options. The application is based on the official YouTube iFrame flutter embedded Player API. which provides users with access to a variety of features for controlling and playing back YouTube videos.

Integration into Flutter Project

Create a new Flutter Project or open existing on where you want to integrate youtube video, Open the Project into your favorite IDE (Android Studio, VSCode, InteliJ…).

Step 1: Include the package youtube_player_flutter

Open pubspec.yaml file and under dependencies section add the package.

youtube_player_flutter:^any

Step 2: You can then run the following command to install the desired package:

flutter pub get

Step 3:  Import the package

Now, to use the youtube video widget, you need to import the dart class as shown below.

import 'package:youtube_player_iframe/youtube_player_iframe.dart';

Requirements to make the package work

Android: Set the minSdkVersion property to 17 in the build.gradle file for your app.

iOS: Swift in iOS Xcode version greater than 11.

defaultConfig {
    applicationId "package name"
    minSdkVersion 17
    targetSdkVersion 30
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

Now, let’s get started on how to use youtube_player_flutter package

Now that our project has been set up and the youtube_player_flutter package has been added in .yaml file.

play the youTube video

1) Create a YoutubePlayerController object

2) Create a YoutubePlayer widget


Creating a YoutubePlayerController Object

The YoutubePlayerController class controls how YouTube videos playback works in our app. When creating an instance of this class we must pass YouTube video ID that we want to play.

YoutubePlayerController _controller = YoutubePlayerController(
  flags: YoutubePlayerFlags(
    autoPlay: true,
    mute: false,
  ),
);

The initialVideoId parameter of the YoutubePlayerController received the YouTube video ID that we want to play.  In the example that was provided that was made. Additionally you have set autoPlay and mute options to  true or false bool value. This means that when the player is ready the sound will turn back on and the video will either start playing or not.

How to Make a YoutubePlayer Widget

The play YouTube video in our flutter application we can create a YoutubePlayerController object and a YoutubePlayer widget . The stateful or stateless YoutubePlayer widget renders the YouTube video player in application using YoutubePlayerController object.

example,

YoutubePlayer(
            controller: _controller,
            showVideoProgressIndicator: true,
            progressIndicatorColor: Colors.blueAccent,
            topActions: <Widget>[
              const SizedBox(width: 8.0),
              Expanded(
                child: Text(
                  _controller.metadata.title,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18.0,
                  ),
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                ),
              ),
            ],
            onReady: () {
              _controller.addListener(listener);
            },
            onEnded: (data) {},
          )

Use the YoutubePlayer widget to display the video:

Note: In addition to adding the following to your project directory AndroidManifest.xml file. you may need enable playing YouTube videos in flutter app .

<uses-permission android:name="android.permission.INTERNET"/>
<application
  android:usesCleartextTraffic="true"
  ...>
  ...
</application>

Error handling

The development of any mobile application including those that make use of the youtube_player_flutter package must include handling errors and exceptions. Although the package offers a simple method for incorporating YouTube videos into your Flutter app errors and exceptions can happen during video playback, which can negatively affect the user experience.

The youtube_player_flutter package offers a number of callbacks that can be used to detect errors , exceptions , handle them. OnPlayerError, OnPlayerStateChange, OnReady, OnEnded and OnPlaybackQualityChange are few of the callbacks.

class VideoPlayerScreen extends StatefulWidget {
  final String ?videoId;

  const VideoPlayerScreen({Key? key, @required this.videoId}) : super(key: key);

  @override
  _VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}

class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  YoutubePlayerController? _controller;

  @override
  void initState() {
    super.initState();
    _controller = YoutubePlayerController(
      initialVideoId: widget.videoId ?? "",
      flags: const YoutubePlayerFlags(
        autoPlay: true,
        mute: false,
      ),
    )
      ..addListener(listener);
  }

  void listener() {
    if (_controller?.value.errorCode != null) {
      print(_controller?.value.errorCode);
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('YouTube Video Player'),
      ),
      body: Center(
        child: YoutubePlayer(
          controller: _controller!,
          showVideoProgressIndicator: true,
          onReady: () {
            print('Player is ready.');
          },
          onEnded: (data) {
            _controller!
              ..load(widget.videoId ?? "")
              ..play();
          },
        ),
      ),
    );
  }
}

Flutter YouTubeVideoPlayer if we want to play the specified video by using the videoId parameter of the VideoPlayerScreen widget. here we have defined in this example youTubeVideo player ID. In order to control video playback speed ,rotation , audio..

We have created the _controller instance and added a listener to handle errors and exceptions in the initState . The listener will print error codein console if one occurs during playback.

We have defined a YoutubePlayer widget in the build method that plays the specified YouTube video using the _controller instance. Additionally, callbacks for the onReady and onEnded events have been defined to address a variety of playback-related conditions.

Click here to access this YouTube player sample app code.  click here…..

Conclusion

Programmers can use the youtube_player_flutter builtin package’s widget to embed YouTube videos in Flutter applications . The widget has a variety of configuration options, including managing audio, displaying video progressValue, and autoPlaying videos.use mainly. This package controls full-screen video playback and makes it possible for users to exit full-screen mode with just one tap.

One of the main benefits of use youtube_player_flutter package is that it provides an easy way to integratation video content into your Flutter app. This package simply the process of including YouTube videos in your application and offers an extensive number of customise option using  improve the look of our videos in flutter app .

Thanks for reading this article….. ❤️

Have a nice day…..

Difference between SharedFlow, StateFlow, LiveData in kotlin

0
Kotlin LiveData, StateFlow, SharedFlow
Kotlin LiveData, StateFlow, SharedFlow

In Kotlin Language SharedFlow, StateFlow, and LiveData are classes that comes with Kotlin Coroutines library which are basically used for communication between component in android application in an asynchronous way. However, there are many key differences in terms of their functionality & use cases.

Difference between SharedFlow, StateFlow, LiveData

1. Kotlin LiveData

In Kotlin language LiveData is a Data Model Class used to hold data and is designed to continously observed by it’s UI components may be activities and fragments. Kotlin LiveData is designed to hold and keep observing data that can be attached to the lifecycle of android component such as Activity or a Fragment. In Other words LiveData automatically handles updates to the UI Component when there are active observers and stops updates when there are no active observers, this helps us in preventing memory leaks. Note that LiveData is not a component or feature of Kotlin Coroutines library. Code Example Below

2. Kotlin Stateflow

In Kotlin StateFlow is a part asynchronous event stream, non-blocking I/O Stream that updates all the subsequent states and it’s current state of the emited data to i;s observers. As I said StateFlow is also a part of Kotlin coroutines library that gives a way to handle and represent state-based data flows. In Kotline StateFlow is used in ViewModel to immediatly update when the state changes to UI components. You might be wondering StateFlow seems similar to LiveData but it offers more flexibility, specially when it is combined with coroutines, as it support you to get control over data emission and transformation. Code Example Below

3. Kotlin Sharedflow

In Kotlin SharedFlow is another way to handle asynchronous stream, non-blocking updates, but unlike as we saw in StateFlow, When a observer starts observing SharedFlow does not emit it’s current state. SharedFlow is been designed for use cases when the initial state is not critical or you can ignore it. SharedFlow is designed in such a way that it allows multiple collectors to receive the emitted values concurrently. Suppose you have multiple subscribers and you want to broadcast data to all the subscribers we can use SharedFlow in Kotlin. Code Example Below



Kotlin LiveData Example

Here is a simple example how to integrate kotlin LiveData

1. Add LiveData dependencies in your android kotlin `build.gradle` file under dependencies section:

dependencies {
    def lifecycle_version = "2.4.0-alpha03"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
}

2. Create a class of which data you want to observe:

data class User(val name: String, val age: Int)

3. Create ViewModel Class that contains a LiveData Object

class UserViewModel : ViewModel() {
    private val _user = MutableLiveData<User>()
    val user: LiveData<User> get() = _user

    fun updateUser(newUser: User) {
        _user.value = newUser
    }
}

4. Now Finally you can keep observe changes of the ‘user’ LiveData Object in your Activity

class MyActivity : AppCompatActivity() {
    private val viewModel by viewModels<UserViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel.user.observe(this, { user ->
            // Update the UI with the new user data
        })

        // Call the update function to trigger the observer
        viewModel.updateUser(User("John Doe", 30))
    }
}


Kotlin Stateflow Example

Here is a simple example how to use kotlin StateFlow into your android application:

1. Add StateFlow dependencies in your android kotlin `build.gradle` file under dependencies section:

dependencies {
    def lifecycle_version = "2.4.0-alpha03"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
}

2. Create a class of which data you want to observe:

data class User(val name: String, val age: Int)

3. Create ViewModel Class that contains a StateFlow Object:

class UserViewModel : ViewModel() {
    private val _user = MutableStateFlow(User("", 0))
    val user: StateFlow<User> get() = _user

    fun updateUser(newUser: User) {
        _user.value = newUser
    }
}

4. Now Finally you can keep observe changes of the ‘user’ StateFlow Object in your Activity or in Fragment by using coroutunes:

class MyActivity : AppCompatActivity() {
    private val viewModel by viewModels<UserViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launch {
            viewModel.user.collect { user ->
                // Update the UI with the new user data
            }
        }

        // Call the update function to trigger the observer
        viewModel.updateUser(User("John Doe", 30))
    }
}


Kotlin Sharedflow Example

Here is a simple example How to use kotlin SharedFlow into your android application:

1. Add SharedFlow dependencies in your android kotlin `build.gradle` file under dependencies section:

dependencies {
    def lifecycle_version = "2.4.0-alpha03"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
}

2. Create a class of which data you want to emit:

data class Message(val text: String)

3. Create ViewModel Class that contains a ShareFlow Object:

class MessageViewModel : ViewModel() {
    private val _messages = MutableSharedFlow<Message>()
    val messages: SharedFlow<Message> get() = _messages

    fun sendMessage(message: Message) {
        viewModelScope.launch {
            _messages.emit(message)
        }
    }
}

4. Now Finally you can keep observe and collect the emitted data/message/changes of the ‘user’ StateFlow Object in your Activity or in Fragment by using coroutunes:

class MyActivity : AppCompatActivity() {
    private val viewModel by viewModels<MessageViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launch {
            viewModel.messages.collect { message ->
                // Do something with the message
            }
        }

        // Call the send function to emit a new message
        viewModel.sendMessage(Message("Hello, world!"))
    }
}