Home Blog Page 14

15 Useful JavaScript Code Snippets

0
JavaScript Code Snippet

Hi Guy’s Welcome to Proto Coders Point, In this Javascript article let’s checkout 15 useful JavaScript code snippets that will help you in various JS Programming tasks

1. Get current Date & Time

To get current date & time in javascript(nodejs), we can make use of Date() below are examples:

// Create a new Date object
const currentDate = new Date();

// Get the current date
const date = currentDate.getDate();

// Get the current month (Note: January is 0) so just add 1.
const month = currentDate.getMonth() + 1;

// Get the current year
const year = currentDate.getFullYear();

// Get the current hours
const hours = currentDate.getHours();

// Get the current minutes
const minutes = currentDate.getMinutes();

// Get the current seconds
const seconds = currentDate.getSeconds();

// Display the current date and time
console.log(`Current Date & Time: ${date}-${month}-${year} ${hours}:${minutes}:${seconds}`);

2. Check if the variable is an array:

To Check if an variable is array or no in JS, We can make use of inbuilt method i.e Array.isArray(), Below is an Example:

// Variable declaration
const myVariable = [1, 2, 3];

// Check if the variable is an array
if (Array.isArray(myVariable)) {
  console.log('The variable is an array.');
} else {
  console.log('The variable is not an array.');
}

3. Merge two arrays:

In Javascript there are two ways by which we can easily merge or concat two arrays: One is by using `concat()` method, another is by using spread operator ('...') Let;s check example of both of them:

Using `concat()` method:

// Arrays to be merged
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

// Merge the arrays using concat()
const mergedArray = array1.concat(array2);

console.log(mergedArray);

Using Spread Operator (…):

// Arrays to be merged
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

// Merge the arrays using the spread operator
const mergedArray = [...array1, ...array2];

console.log(mergedArray);

convert array to collection in javascript


4. Remove duplicates from an array:

In JavaScript, there are many ways by which we can remove any duplicates from a given list by using inbuilt methods: Let’s check them one by one.

Using Set Object:

const array = [1, 2, 3, 3, 4, 5, 5];

const uniqueArray = [...new Set(array)];

console.log(uniqueArray);

The 'Set' Object is used by which a new set from the array is created, the Set will automatically remove the duplicate values, Then, In above example I have made use of Spread operator '...' to convert the new Set to Array.

converting list to set or set to list in dart


Using the filter() method:

const array = [1, 2, 3, 3, 4, 5, 5];

const uniqueArray = array.filter((value, index, self) => {
  return self.indexOf(value) === index;
});

console.log(uniqueArray);

we can also make use of filter() method in javascript to remove duplicate from a array, The filter() method has a callback function. The callback function checks if the index of current element is same as of first occurrences and thus it is added into uniqueArray variable.


Using the reduce() method:

const array = [1, 2, 3, 3, 4, 5, 5];

const uniqueArray = array.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);

console.log(uniqueArray);

The reduce() method will iterate to the given array and here while iterating to each item from the array we check is it already included in new array by includes() method, If not Included then push the currentValue (Index Item) Into the new array.

The Above Example will create a new array variable with content [1, 2, 3, 4, 5], removing all the duplicates occurrences.


5. Sort an array in ascending order:

To Sort an array in javascript, let’s make use of `sort()` method, Here’s an example:

const array = [3, 1, 4, 2, 5];

// Sort the array in ascending order
const sortedArray = array.sort((a, b) => a - b);

console.log(sortedArray);

6. Reverse an array:

To reverse an array, will make use of reverse() method, Here’s an example:

const array = [1, 2, 3, 4, 5];

// Reverse the array
const reversedArray = array.reverse();

console.log(reversedArray);

On an given array, we can apply reverse() method, it will simply reverse all the element from the original array and create a new Array.


7. Convert string to number:

In JavaScript, To convert string to an number, we can make use of parse method i.e. parseInt() or parseFloat() let’s see an example:

Using parseInt() to convert string to integer

const stringNumber = "42";
const number = parseInt(stringNumber);

console.log(number);

Using parseFloat() to convert a string to float-point number

const stringNumber = "3.14";
const number = parseFloat(stringNumber);

console.log(number);

8. Generate a random number between two values:

In JavaScript, To generate a number between a given range we can make use of Math.random() method, Here is an example:

const min = 1;   // Minimum value
const max = 10;  // Maximum value

// Generate a random number between min and max
const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;

console.log(randomNumber);

9. Check if a string contains a substring:

To check is a given string variable contain a particular world or substring we can either use includes() or indexOf() method, Let’s understand this will code snippets:

Using includes() method:

const string = "Hello, world!";
const substring = "world";

// Check if the string contains the substring
const containsSubstring = string.includes(substring);

console.log(containsSubstring);

Using indexOf() method:

const string = "Hello, world!";
const substring = "world";

// Check if the string contains the substring
const containsSubstring = string.indexOf(substring) !== -1;

console.log(containsSubstring);

10. Get the Length of an Object:

In JS, Objects don’t has any inBuilt method or function to get the length of an object like arrays has, But as object has key-value pair elements in it we can get length of an object using key or value, Below is an example:

const myObject = {
  name: "John",
  age: 30,
  city: "New York"
};

// Get the length of the object
const objectLength = Object.keys(myObject).length;

console.log(objectLength);

The Object.keys() method is used to retrieve an array of the object keys and then ‘length’ property is used on the array to get the number of keys in an object.


11. Convert Object to array:

To convert an object into array in JS, We will use Object.entries() method:

const myObject = {
  name: "John",
  age: 30,
  city: "New York"
};

// Convert the object to an array
const objectArray = Object.entries(myObject);

console.log(objectArray);

In this code snippet, the Object.entries() method is called on the myObject object. It returns an array of arrays, where each inner array contains two elements: the key and the corresponding value from the object.

The resulting array, objectArray, will look like this:

[ 
  ["name", "John"],
  ["age", 30],
  ["city", "New York"]
]

12. Check if an object is empty:

To check of an object is empty we can use either of this two method i.e Object.keys() or Object.entries(), Example code snippet below:

Using Object.keys() to check if object is empty:

const myObject = {};

// Check if the object is empty
const isEmpty = Object.keys(myObject).length === 0;

console.log(isEmpty);

Using Object.entries() to check if object is empty:

const myObject = {};

// Check if the object is empty
const isEmpty = Object.entries(myObject).length === 0;

console.log(isEmpty);

13. get current URL:

In browser, If you want to add feature to your application to get the current URL using JavaScript we can make use of window.location Here is an example:

var currentURL = window.location.href;
console.log(currentURL);

The above code, window.location.href browser property will return the complete URL.


14. Redirect to a new URL:

In Javascript, to redirect a user to desired URL we can make use of window.location with assign() method or by using window.location.href. Here’s an example of how to redirect to a URL:

window.location.assign("https://www.example.com");
window.location.href = "https://www.example.com";

15. Copy text to clipboard

In Javascript, to copy a text to a clipboard, we can make use of document.execCommand('copy'); method or by using Clipboard API both the code example are given below:

using Clipboard API method:

Here to copy the content we are using clip API writeText() function to copy/write the text content into clipboard.

const textToCopy = "Text to copy";
navigator.clipboard.writeText(textToCopy)
  .then(() => {
    console.log("Text copied to clipboard");
  })
  .catch((error) => {
    console.error("Error copying text to clipboard:", error);
  });

Using document.execCommand()

const textToCopy = "Text to copy";
var tempInput = document.createElement("input");
tempInput.value = textToCopy;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand("copy");
document.body.removeChild(tempInput);
console.log("Text copied to clipboard");

Different between compileSdkVerion & targetSdkVersion android

0
Different Between 𝐜𝐨𝐦𝐩𝐢𝐥𝐞𝐒𝐝𝐤𝐕𝐞𝐫𝐬𝐢𝐨𝐧 and 𝐭𝐚𝐫𝐠𝐞𝐭𝐒𝐝𝐤𝐕𝐞𝐫𝐬𝐢𝐨𝐧

In this android blog article, Let’s Understand the major different between compileSdkVersion & targetSdkVersion in Android Development, This both CompileSdkVersion and TargetSdkVersion are very important settings that is configured into Android project while creating new project under build.gradle file. They simply tells developer that which Android SDK version is been used to compile the code & which while be highest device it the app will support. Here’s the difference between the two:

Android compileSdkVersion

𝐜𝐨𝐦𝐩𝐢𝐥𝐞𝐒𝐝𝐤𝐕𝐞𝐫𝐬𝐢𝐨𝐧 specifies which version of Android SDK will be used by android gradle to compile you android project. This means that your andriod application has the ability to use all that APIs is is been included into the specified version and less then specified version.

𝐅𝐨𝐫 𝐄𝐱𝐚𝐦𝐩𝐥𝐞, If your android project is set to 𝐜𝐨𝐦𝐩𝐢𝐥𝐞𝐒𝐝𝐤𝐕𝐞𝐫𝐬𝐢𝐨𝐧 to 30, it means that your android application has access to use all the APIs up to version 30. For example, let’s assume you want Camera2 API to be used, But the Camera2 API was introduced with Android 5.0 (i.e. API Level 21) and above, and you have already set 𝐜𝐨𝐦𝐩𝐢𝐥𝐞𝐒𝐝𝐤𝐕𝐞𝐫𝐬𝐢𝐨𝐧 to 30, That means you can use Camera2 API without any issue. However, suppose you set compileSdkVersion lower then API Level 21 and you are trying to make use of Camera2 API, then you will get compile-time error because Camera2 API is not available below 𝐜𝐨𝐦𝐩𝐢𝐥𝐞𝐒𝐝𝐤𝐕𝐞𝐫𝐬𝐢𝐨𝐧 21.

Android targetSdkVersion

𝐭𝐚𝐫𝐠𝐞𝐭𝐒𝐝𝐤𝐕𝐞𝐫𝐬𝐢𝐨𝐧 This version defines tell the android OS on which android SDK version the Application was designed and tested on and also indicates the API version the app is of compatibility and can run smoothly.

𝐅𝐨𝐫 𝐄𝐱𝐚𝐦𝐩𝐥𝐞, suppose your android project 𝐭𝐚𝐫𝐠𝐞𝐭𝐒𝐝𝐤𝐕𝐞𝐫𝐬𝐢𝐨𝐧 is set to 30, It Means that you has designed the app to run on device that support android 30 and above, and you made it sure that your android application will work smoothly abd behaves correctly as accepted on those devices.

Conclusion

📝 The summary, the compileSdkVersion, determines a set of APIs that is been used for the build process, while the targetSdkVersion specifies the intended API level for the app and indicates its compatibility with newer Android versions.

🎯 Ideally, the compileSdkVersion and targetSdkVersion should match, both pointing to the latest SDK. However, it’s crucial to thoroughly test the app’s compatibility with the changes introduced in that version.

💡 Therefore, understanding the distinction between compileSdkVersion and targetSdkVersion is vital for effective utilization in Android development projects. This ensures optimization, thorough testing, and smooth functioning of your app across various devices. Happy coding! 💻📱🚀

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