Home Blog Page 25

Firebase dynamic link in flutter

0
firebase dynamic links in flutter

By using dynamic linking, increase user experience, engagement, and retention

You may redirect both current and potential users to any point within your iOS or Android app using dynamic links, which are clever URLs. Even new users see the content they’re seeking for when they open the app for the first time because they survive the app installation process. Dynamic Links are always free, regardless of scale.

What distinguishes a static link from a dynamic link

For managing deep linking for applications and websites, Firebase Dynamic Links offers a wealth of features. The nicest aspect is that any scale of Firebase deep connection is free. Instead of sending the user to the Play Store, dynamic links improve the user experience by leading him to the intended equivalent site or app content. This appears to be helping to develop, improve, and expand applications for various platform domains.

Firebase Dynamic Links: 

The following circumstances are handled by Firebase Dynamic Links:

  • If a user clicks on one of your dynamic links, they will be instantly sent to the play store or app store to download your app in order to view the link.
  • Opening the link will launch the programme on the device if it is installed but not currently running in the foreground.
  • The user can access a dynamic link in the registered listener if the app is in the forefront.

How to integrate Dynamic Links in flutter using Firebase

Initial Configuration & Setup

First and foremost, we set up our Firebase project to support dynamic linking. Click on the link below to start your firebase project.

Log in to the Firebase console, then click Add project.

Open the firebase console and tap the “Add project option” , and get this type of screen.

Here add your firebase project name.

  1. Select your existing Google Cloud project from the dropdown menu, then click Continue.
  2. (Optional) Select or create a Google Analytics account after enabling Google Analytics for your project.
  3. When you’re finished, scroll down and select “Create Project.”

The firebase console might take some few seconds to go through your application. Once everything is done, click the proceed button to see the project overview page.

Select here Android or/ and IOS platform.

You can skip this step if you have already configured your project for Dynamic Links.

Firebase Dynamic Links From the Firebase console setting 

  • Launch the Firebase console. Open the Firebase project where Firebase Dynamic Links need to be added.
  • Configure your Firebase project’s App: (Android, iOS) option.
  • The Dynamic Links section will appear after the Grow Section.
  • To create a URL prefix, now click Get Started.
  • Make a dynamic link with the app’s distinctive domain name in it. Using firebasedynamiclinks.page.link as an illustration. Here, the suffix page.link is added to the domain name.
  • then perform the steps to Configure, Verify, and Finish.

The first step is, Enter your domain here and press the continue button , 

Dynamic links are created on a domain, which you can modify by adding your own name, company name, brand, and so on. Customized links appear more relevant and Display this dialogue, then click Finish.

The following screen will then display this dialog.

Click on the three dots on the right side, then select Allowlist URL pattern, then enter the link below and click on the add option.

Create a dynamic link inside the Firebase Console

a). Click the image below into the “New Dynamic link” button.

b). Set up a short URL link and then click “Next”.

Set up for short dynamic link

Put your custom URL in the URL prefix header.

c). Then, in the second step “Set up your Dynamic Link,” enter the URL for your dynamic link. There is a deep link to your application, and if a specific user has not installed the app, he or she should be redirected to the appropriate location. As an example, as the dynamic link, you could provide an app play store link. You can give your dynamic link any meaningful short name you want. Click the “Next” button.

add the dynamic link URL & name.

d). in the fourth step of Select the “Open the deep link URL in a browser” option. If the specific app is not installed in your app, the link will open in the browser. If you don’t have an iOS app, you can select “Open the deep link in your iOS App.” Then press the “Next” button.

Choose link behavior for ios.

e). In this section, we define Android behavior. Choose “Open the deep link in your Android App” and enter the name of your Android app. Then press the “Next” button.

Choose link behavior for android.

f). You can also change some advanced settings. Then click “Create”.

Now , let’s move to the Flutter code side…

Installing the plugin for Firebase Dynamic Links:

There are packages available for Flutter that give users access to many different services on each platform.

Step : 1) Open the pubspec.yaml file in the project’s root directory, then add the following package:

firebase_dynamic_links: ^any

Step : 2) Get the flutter packages.

Add the command on specific IDE terminal flutter packages get

This will allow you to add Firebase Dynamic Links to your Flutter project.

Create a Dynamic Link In Programming

Make a dynamic Link instance.

FirebaseDynamicLinks dynamicLinks = FirebaseDynamicLinks.instance;

Add the function for create dynamic link

Future<void> _createDynamicLink() async {
 final DynamicLinkParameters parameters = DynamicLinkParameters(
   uriPrefix: 'https://croudoperationapp.page.link',
   link: Uri.parse(
     "https://croudoperationapp.page.link/referral?code=12345&amp;userId=${123)}"),
   androidParameters: const AndroidParameters(
     packageName: 'Add your app package name',
     minimumVersion: 0,
   ),
   iosParameters: const IOSParameter(
     bundleId: 'Add your app bundle Id',
     minimumVersion: ‘0’,
     appStoreId: ‘Add your app store Id’
   ),
   socialMetaTagParameters: SocialMetaTagParameters(
    title: "Example of a Dynamic Link",
    imageUrl: Uri.parse("https://example.com/image.png"),
  ),
 );
}

Use the DynamicLinkParameters instead of the DynamicLinkParameters to create a short Dynamic Link. method buildShortLink()

String? _deepLink;

 final ShortDynamicLink shortLink =
     await dynamicLinks.buildShortLink(parameters);
 Uri url = shortLink.shortUrl;
 setState(() {
   _deepLink = url.toString();
 });

Use the DynamicLinkParameters to abbreviate a lengthy Dynamic Link. method shortenUrl

call the _createDynamicLink function on the button where to create a link.

FloatingActionButton.extended(
 backgroundColor: Theme.of(context).colorScheme.primary,
 onPressed: () async {
   await _createDynamicLink();
   print(_deepLink);
   if (_deepLink != null) {
     Share.share(_deepLink!);
   }
 },
 icon: const Icon(
   Icons.share,
   color: Colors.white,
 ),
 label: const Text(
   "Referral code",
   style: TextStyle(color: Colors.white),
 ),
)

Add the code into the main.dart file.

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await GetStorage.init();
  runApp(
    MaterialApp(
      title: 'Dynamic Links Example',
      debugShowCheckedModeBanner: false,
      home: const LoginPage(),
      theme: ThemeData(
        colorScheme: defaultColorScheme,
        primarySwatch: Colors.blue,
      ),
      builder: EasyLoading.init(),
    ),
  );
}

Now, Handling dynamic links and redirecting them to particular content.

Void handleDynamicLink(){

var data = await FirebaseDynamicLinks.instance.getInitialLink();
var deepLink = data;

if (deepLink != null) {
  // kill state dynamic link handling here
  //navigate here
}

 dynamicLinks.onLink.listen((dynamicLinkData) async {
 print('on listen');
           print(dynamicLinkData.link.queryParameters["code"]);
   // open and not terminated state dynamic link handling here
  //navigate here
    }).onError((error) {
      print('onLink error');
      print(error.message);
    });
}

Github code link for reference:

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

Flutter Dynamic Link – Integrating Refer & earn in app

Conclusion 

In the post, I showed the fundamental structure of dynamicLink; you may adapt this code to suit your needs, and this was a brief introduction to dynamicLink using Firebase and how it works with Flutter.

Thank you !!! Have a good day 😊 😊 ..

Basic Windows command everyone should know

0
windows cmd

Hi, Here are some basic windows command that everyone one should remember.

1. Create New Folder

mkdir -> make directory / Create a new folder in the working directory.

mkdir [directory name]

2. Change director/navigate to directory

cd -> Change directory let you to navigate directory & access different folders.

cd [folder/directory name]
windows cmd to change working directory folder

3. List all files

dir -> List the files & folders contained in the current working directory.

dir
windows command to list file in current working directory
windows command to list file in current working directory

4. Rename folder or file name

ren -> to re-name files or folder name.

ren [old folder name] [new folder name]

5. Copy file

copy -> copies the files to specified folder.

copy [file] [destination]

5. Delete file

del -> delete files or folder

del folder Name
del file name

What is git? Why we use GitHub

0
Why we use GitHub

GitHub is a platform by which you can collaboration and version control your project. That enables you & your team to remote collaboration on projects.

Why we use GitHub

Version Control

  • Git is a version control system.
  • Version control is used to track changes and manage code.
  • Version Control system are used by any type of developer as a part of their workflow.

Staging Environment

  • git has it’s own staging envirnoment.
  • By using staging envirnoment, you can make changes to the working directory.
  • Staging makes it easier to adjust what you commit.

Branches

  • Branch help you structure new changes.
  • By using branches, you can work on your repository without any risk.
  • when finished and finalizing the code, your branch can be merged with master/main github branch.

Collaboration

  • When working with other programmers, git comes in handy as a collaboration tool.

As version control is a necessory part of development, Git knowledge is needed in most developers job.

React vs Angular – Difference between react and angular

0
difference between react and angular
React vs Angular

Hi Guys, Welcome to Proto Coders Point. In this Article let’s check out the difference between react and angular.

Difference between react and angular

ReactAngular
React is a JS library developed by Facebook which allows us in building UI Components. It facilitates the creation of interactive user interface.Angular is a structured framework from developing dynamic web apps. It allows developers to use HTML as a template and allow HTML’s syntax to express the application’s components briefly and clearly.
FeatureFeatures of ReactJS is Code reusability, Rich JavaScript library, one -way data binding.Feature of Angular is Testing, Creating templates, accessibility, low-code framework.
Easy to learnIt is easier to grasp compared to angular. However, When it come integrating with Redux it become difficult.Learning Angular is not easy for beginners. This, Angular require lot’s of training.
When dynamic content is required, React.js is suggested.Angular is platform-independent and hence is compatible to work in any platform.
LanguageReact.js written using JavaScript.Angular uses microsoft’s TypeScript language, Which is a super set if ECMAScript 6 (ES6).
InjectionReact.js, Does not use the dependencies Injection concept.Angular Hierarchical Dependency Injection system is used.
Data-BindingIn react Data binding is one-way type.In react Data binding is two-way type.
App BuildInstagram, Yahoo, Netflix, Facebook, Dropbox, Uber etc are build using React.Microsoft, Apple, GoPro, Mesh, Telegram, Google, Paypal..etc are using Angular.

Recommended Article

Learn Angular – Build first web app using angular

Flutter vs React native

7 best tools for react development

How to use bootstrap in React

How to create custom hooks in react

How do I turn off refresh rate hz that is always showing on MSI Monitor Screen

0

I recently got a new MSI optix G241 monitor, and on a left corner of monitor their is a screen refresh rate been showing.

Let’s check out how to display refresh rate hz showing on monitor screen.

Solution:

On MSI monitor on back there is a small red joystick button using which you can change MSI monitor settings.

Follow this Step to disable refresh rate been show in screen.

  • Open Monitor Menu – Click red button on back of monitor.
  • Select Gaming Option.
  • then select Refresh Rate.
  • and then turn it off.

RazorPay Payment integration in flutter with source code example

0
Razorpay Integration in Flutter App
Razorpay Integration in Flutter App

In this Flutter Article let’s explore about Razorpay a payment gateway and learn how to integration it into our flutter application.

What is Razorpay

Razor pay if basically a payment gateway/portal, A secure payments service provider called Razorpay (www.razorpay.com) accepts a variety of payment methods, including credit and debit cards, UPI, and some mobile wallets.

Through its product line, Razorpay enables your company to accept, handle, and distribute payments. One of the greatest payment gateways that offers a plugin quickly is Razor Pay. We started working with Razorpay because they had the easiest in-product payment widget to integrate, but we have continued to work with them because of their prompt and consistent support for both problem resolution and adding new features.

The majority of businesses today, like Zomato, Goibibo, Zoho, Spicejet, BookMyShow, Nykaa, Urbanclap, and many others, use Razorpay in their 

applications. Razorpay offers mobile wallets, credit and debit cards, and UPI as payment options. The fastest growing firm in India and a provider of online payment services is Razorpay.

How does razorpay work

Razorpay contacts the acquiring bank with a capture request on behalf of the merchant. After that, the funds are transferred from the issuing bank to the acquiring bank. The transaction money is then settled to the merchant by Razorpay in collaboration with the acquiring bank.

Therefore, let’s begin the step-by-step tutorial for adding Razorpay to a flutter application.

Getting Started

Razorpay Payment Gateway

1. Create a Account/Login into razorpay

Firstly you need to create a account and get signIn into razorpay and access the dashboard.

2. Get API key from razorpay

razorpay test mode
razorpay test mode

Here choose whether you are willing for testing or live, depending on that create an API key as show below.

1. For a key to be generated for the selected mode (testing or live), navigate to Settings API Generate Key.

razor pay create test api key
razor pay create test api key

Note for key:

  • For the test and live modes, distinct API Keys must be generated. In test mode, no money is taken from your real account.

Razorpay Integration in flutter

Create or open a flutter application where you want to payment gateway to accept payments from your app user.

Implementation:

Step 1: Adding Required external dependencies

razorpay_flutter: any
http: any
fluttertoast: any

http:

Http is a flutter plugin that will help you in making HTTP requests.

fluttertoast

enables you to display a toast message in your flutter.

razorpay_flutter:

Is a plugin that allows you to include Razorpay into your flutter application and take user payments. Both iOS and Android are supported by this plugin. You can review the following documentation:

Android: https://razorpay.com/docs/checkout/android/

iOS: https://razorpay.com/docs/ios/


Step 2: Import razorpay_flutter

Now you need to import it where you want to integrate payment portal.

import 'package:razorpay_flutter/razorpay_flutter.dart';

Notes about Android/IOS platform requirement:

  • The required minimum version is:
    Make sure your app’s base minimum API level is 19 or greater for Android.
  • Make sure iOS 10.0 or above is the minimum deployment target for your app. Remember to enable bitcode for your project as well.

Step 3: Implementing razor pay in flutter

Make an instance of Razorpay:

To create a Razorpay instance, use this code.

Razorpay? _razorpay = Razorpay();

Event Listeners:

This plugin uses event-based communication and emits the event of a successful or unsuccessful payment.

The constants

  • EVENT PAYMENT SUCCESS.
  • EVENT PAYMENT ERROR.
  • EVENT EXTERNAL WALLET.

To add event listeners, use the Razorpay instance’s on(String event, Function handler) method.

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

In the Razorpay class, these events are designated as constants. The following code demonstrates how to handle events by establishing listener methods for each individual event:

Events is:

 @override
  void initState() {
    super.initState();
    _razorpay = Razorpay();
    _razorpay?.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
    _razorpay?.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
    _razorpay?.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
  }

initial step to create Instance is completed, Now let’s move to app page creation for payment gateway integration in flutter app.


Create a file name payment_page.dart

Import following package

import 'package:fluttertoast/fluttertoast.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';

Now, The razorpay instance and payment event listeners should now be initialized in the initState() function.

 @override
  void initState() {
    super.initState();
    _razorpay = Razorpay();
    _razorpay?.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
    _razorpay?.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
    _razorpay?.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
  }

function to handle razorpay payment

void _handlePaymentSuccess(PaymentSuccessResponse response) {
    Fluttertoast.showToast(
        msg: "SUCCESS PAYMENT: ${response.paymentId}", timeInSecForIosWeb: 4);
  }

  void _handlePaymentError(PaymentFailureResponse response) {
    Fluttertoast.showToast(
        msg: "ERROR HERE: ${response.code} - ${response.message}",
        timeInSecForIosWeb: 4);
  }

  void _handleExternalWallet(ExternalWalletResponse response) {
    Fluttertoast.showToast(
        msg: "EXTERNAL_WALLET IS : ${response.walletName}",
        timeInSecForIosWeb: 4);
  }

Here I am simply showing a toast message whenever any payment event happens.

Function that opens payment interface

To open the payment interface, create a function called openPaymentPortal() that takes several parameters like:

  • API key.
  • order id.
  • amount.
  • name.
  • description.

These parameters are stored in the options variable, which is passed to the razorpay.open function.

Razorpay option request parameter

key:Your API key that you get for razorpay dashboard in setting option.
amount:Her the amount for the transaction should by passed. The amount should be in paise in case of INR. Eg: Rs. 300 is the transaction amt, them the value to be passed in this option field should be 30000.
currency:Length must be 3 char, The currency transaction should be make Eg:INR. see the supported currencies list.
name:A business name shown during payment checkout.
prefill:Contact: A Phone number of your customer.
Email: A Email Id of your customer.
void openPaymentPortal() async {
    var options = {
      'key': 'rzp_test_YjOu38M2dxdNJ5',
      '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());
    }
  }

Now Create a Button when clicked calls openPaymentPortal() and proceed to payment.

 InkWell(
            onTap: () {
              openChecF();
            },
            child: Padding(
              padding: const EdgeInsets.only(left: 18.0, right: 18),
              child: Container(
                  width: MediaQuery.of(context).size.width - 60.0,
                  height: 50.0,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20.0),
                      color: Colors.blue.shade900),
                  child: Center(
                      child: Text('Pay',
                          style: TextStyle(
                              fontSize: 16.0,
                              fontWeight: FontWeight.w900,
                              color: Colors.blue.shade50),
              ),
          ),
       ),
   ),
)

Response to successful payment:

Payment_id: string the payment’s ID.

Order iD: If the payment was for an order, the order ID; otherwise, null.

Signature: string the signature that will be used to confirm payment. Only applicable to orders; if not.


Response to a failed 

Code value : integer the error message

message value : message the message of error.

Response to a External Wallet Response:

String the chosen external wallet’s name.


Complete Source Code – Flutter RazorPay implementation

main.dart

From main page I am simple rendering payment page.

import 'package:flutter/material.dart';
import 'paymentPage.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Razorpay implement app',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const PaymentPage(),
    );
  }
}

paymentPage.dart

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';

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

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

class _PaymentPageState extends State<PaymentPage> {
  Razorpay? _razorpay;

  @override
  void initState() {
    super.initState();
    _razorpay = Razorpay();
    _razorpay?.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
    _razorpay?.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
    _razorpay?.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
  }

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

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

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

  void _handlePaymentSuccess(PaymentSuccessResponse response) {
    Fluttertoast.showToast(
        msg: "SUCCESS PAYMENT: ${response.paymentId}", timeInSecForIosWeb: 4);
  }

  void _handlePaymentError(PaymentFailureResponse response) {
    Fluttertoast.showToast(
        msg: "ERROR HERE: ${response.code} - ${response.message}",
        timeInSecForIosWeb: 4);
  }

  void _handleExternalWallet(ExternalWalletResponse response) {
    Fluttertoast.showToast(
        msg: "EXTERNAL_WALLET IS : ${response.walletName}",
        timeInSecForIosWeb: 4);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.blue.shade900),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        title: const Text('Payment',
            style: TextStyle(fontSize: 22.0, color: Color(0xFF545D68))),
      ),
      body: Column(children: [
        const SizedBox(height: 16.0),
        Center(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Card(
              child: Column(
                children: <Widget>[
                  Text(
                    '\$1.88',
                    style: TextStyle(
                        fontSize: 22.0,
                        fontWeight: FontWeight.bold,
                        color: Colors.blue.shade900),
                  ),
                  const SizedBox(height: 10.0),
                  const Text(' Ice Cream',
                      style: TextStyle(color: Colors.grey, fontSize: 24.0)),
                ],
              ),
            ),
          ),
        ),
        const SizedBox(height: 18.0),
        InkWell(
            onTap: () {
              openPaymentPortal();
            },
            child: Padding(
              padding: const EdgeInsets.only(left: 18.0, right: 18),
              child: Container(
                  width: MediaQuery.of(context).size.width - 60.0,
                  height: 50.0,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20.0),
                      color: Colors.blue.shade900),
                  child: Center(
                      child: Text('Pay',
                          style: TextStyle(
                              fontSize: 16.0,
                              fontWeight: FontWeight.w900,
                              color: Colors.blue.shade50)))),
            ))
      ]),
    );
  }
}

Conclusion

The above is a small flutter example that help you to integrate Razorpay payment. In this code, you will see how to add Razorpay to flutter app and how to acquire an order with online payment. The below image demonstrates how Razorpay Payment will function.

flutter razorpay example

Thanks for spending time reading this content…..

The source code for this App , connected with Razorpay may be seen on GitHub please click here -> https://github.com/Mitali8620/razorpay_flutter.git