Saturday, March 30, 2024

New Concept For BottomNavigationBar in Flutter

 Hey Friends ! Whats-uppppp, I am back with my limited knowledge 😂😁 in flutter but it is important for you.

So Today we are going to know, when we navigate through BottomNavigationBar and click on back button it does not trace previous visited BottomNavigationItem, if you are learning flutter from youtube.

They suggest to take List<Widget> screen and render the Widget via index of screens. Personally i think, it is not better to remove widget suddenly from widget tree.

So finally i came with this new code:

We are going to use get package for state-management here also simple flutter code:

Create file bottom_navigation_screen.dart:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:badges/badges.dart' as badges;

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

  final BottomNavigationController
_bottomNavigationController =
    Get.put(BottomNavigationController());

   final PageController _pageController
= PageController(initialPage: 0);
  List<Widget> screens = [
    HomeScreen(),
    ProfileScreen(),
    SearchScreen(),
    CartScreen()
  ];

  @override
  Widget build(BuildContext context) {
  return Obx(() {
  return PopScope(
  canPop: _bottomNavigationController
    .wantBack.value,
  onPopInvoked: (bool didPop) async {
  print(didPop);
  if (didPop) return;
  if (_bottomNavigationController
    .visitedIndexes.length > 1) {
  _bottomNavigationController.visitedIndexes
   .removeLast(); // Remove current index
   _pageController.animateToPage(
    _bottomNavigationController.visitedIndexes.last,
    duration: Duration(milliseconds: 300),
                curve: Curves.linear);
            _bottomNavigationController.stackIndex.value =
                _bottomNavigationController
                    .visitedIndexes.last; // Go back to previous index

            return;
          } else {
            _bottomNavigationController.wantBack.value = true;
            Get.back();
          }
        },
        child: Scaffold(
          body: PageView.builder(
            physics: NeverScrollableScrollPhysics(),
            itemCount: screens.length,
            controller: _pageController,
            itemBuilder: (BuildContext context, int index) {
              return screens[index];
            },
          ),
          bottomNavigationBar: BottomNavigationBar(
            currentIndex: _bottomNavigationController.stackIndex.value,
            selectedItemColor: Colors.amber,
            unselectedItemColor: Colors.black,
            elevation: 5,
            onTap: (int index) {
              if (!_bottomNavigationController.visitedIndexes.contains(index)) {
                _bottomNavigationController.visitedIndexes
                    .add(index);
// Add index to visited indexes list
              }
              _bottomNavigationController.stackIndex.value = index;
              _pageController.animateToPage(index,
                  duration: Duration(milliseconds: 300), curve: Curves.linear);
                          },
            items: [
              BottomNavigationBarItem(
                  icon: CustomIcons.homeOutline(),
                  activeIcon: CustomIcons.home(
                      color: CustomColors.amber,
                  label: 'Home'),
              BottomNavigationBarItem(
                  icon: Icon(Icons.person_outline),
                  activeIcon: Icon(Icons.person),
                  label: 'Profile'),
              const BottomNavigationBarItem(
                  icon: Icon(Icons.search), label: 'Search'),
              BottomNavigationBarItem(
                  icon: Icon(Icons.cart_outline),
                  activeIcon: Icon(Icons.cart,color: Colors.amber,), 
                  label: 'Cart'),
            ],
             
          ),
        ),
      );
    }
    );
  }
}


Create another file
bottom_navigation_controller.dart:


import 'package:get/get.dart';

class BottomNavigationController extends GetxController {
  final stackIndex = 0.obs;
  final visitedIndexes = <int>[0].obs;
// Keep track of visited indexes
  final wantBack = false.obs;
}




Tuesday, March 26, 2024

Easiest way to center a div

Most of the time, interviewers ask interviewees about having two divs, one being the parent and the other being the child. Your task is to center the child div.

To understand the properties required to center the div, we need to understand some other properties:

Position: There are generally three types of positions:

  • relative (Default)
  • absolute
  • static
  • fixed

There are several methods to center a div within its parent div in HTML and CSS. Here are some common methods:

  1. 1. Using Flexbox:

    css
    .parent { display: flex; justify-content: center; /* Horizontally center */ align-items: center; /* Vertically center */ }
  2. 2. Using Grid:

    css
    .parent { display: grid; place-items: center; }
  3. 3. Using Absolute Positioning:

    csscode
    .parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
  4. 4. Using Grid with Flexbox Fallback (for older browser support):

  5. css
    .parent { display: grid; } .child { justify-self: center; align-self: center; display: flex; }

Each of these methods has its advantages and may be more suitable depending on the specific layout requirements and browser support considerations of your project. Flexbox and Grid are the most commonly used methods due to their flexibility and ease of use for complex layouts.

Integrate Cashfree Payment Gateway in Flutter

Payment Gateway:

payment gateway is a merchant service provided by an e-commerce application service provider that authorizes credit card or direct payments processing for e-businessesonline retailersbricks and clicks, or traditional brick and mortar.[1] The payment gateway may be provided by a bank to its customers, but can be provided by a specialised financial service provider as a separate service, such as a payment service provider.

A payment gateway facilitates a payment transaction by the transfer of information between a payment portal (such as a website, mobile phone or interactive voice response service) and the front end processor or acquiring bank.

Payment gateways are a service that helps merchants initiate ecommerce, in-app, and point of sale payments for a broad variety of payment methods. The gateway is not directly involved in the money flow; typically it is a web server to which a merchant's website or POS system is connected. A payment gateway often connects several acquiring banks and payment methods under one system.


To Integrate cashfree Payment Gateway into your flutter project follow these step only (For Android) :

Step 1.


install this dependancy after runing this command in terminal:

flutter pub get flutter_cashfree_pg_sdk

Step 2.



// Please put cursor on every import where it is break the line
// and make it one liner

import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_cashfree_pg_sdk/api/cferrorresponse
/cferrorresponse.dart';
import 'package:flutter_cashfree_pg_sdk/api/cfpayment
/cfdropcheckoutpayment.dart';
import 'package:flutter_cashfree_pg_sdk/api/cfpaymentcomponents
/cfpaymentcomponent.dart';
import 'package:flutter_cashfree_pg_sdk/api/cfpaymentgateway
/cfpaymentgatewayservice.dart';
import 'package:flutter_cashfree_pg_sdk/api/cfsession
/cfsession.dart';
import 'package:flutter_cashfree_pg_sdk/api/cftheme
/cftheme.dart';
import 'package:flutter_cashfree_pg_sdk/utils
/cfenums.dart';
import 'package:flutter_cashfree_pg_sdk/utils
/cfexceptions.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;


class PaymentMethodScreen extends StatefulWidget {
  const PaymentMethodScreen({super.key});

  @override
  State<PaymentMethodScreen> createState() =>
_PaymentMethodScreenState();
}

class _PaymentMethodScreenState extends
State<PaymentMethodScreen> {
 
  CFPaymentGatewayService cfPaymentGatewayService =
      CFPaymentGatewayService(); // Cashfree Payment Instance
  bool? isSuccess;

  @override
  void initState() {
    super.initState();
    // Attach events when payment is success and
// when error occured
    cfPaymentGatewayService.setCallback(verifyPayment, onError);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Payment Method'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          ListTile(
            onTap: () {
              pay();
            },
            title: Text("Online Pay"),
          ),
        ],
      ),
    );
  } // When payment is done successfully

  void verifyPayment(String orderId) {
    // Here we will only print the statement
    // to check payment is done or not
    isSuccess = true;
    setState(() {});
// redirect to final screen from here
 
    print("Verify Payment $orderId");
  }

// If some error occur during payment this will trigger
  void onError(CFErrorResponse errorResponse, String orderId) {
    // printing the error message so that we can show
    // it to user or checkourselves for testing
    isSuccess = false;
    setState(() {});
    print(errorResponse.getMessage());
    print("Error while making payment");
  }

  String orderId = new DateTime.now()
    .millisecondsSinceEpoch
    .toString();

  Future<CFSession?> createSession() async {
    try {
     
final mySessionIDData = await createSessionID(
          orderId);
// This will create session id from flutter itself

     

      print(mySessionIDData);

      // Now we will se some parameter like orderID ,
        //environment,payment sessionID
      // after that we wil create the checkout session
      // which will launch through which user can pay.
      var session = CFSessionBuilder()
          .setEnvironment(CFEnvironment.SANDBOX)
          .setOrderId(mySessionIDData["order_id"])
          .setPaymentSessionId(
            mySessionIDData["payment_session_id"])
          .build();
      return session;
    } on CFException catch (e) {
      print(e.message);
    }
    return null;
  }

  pay() async {
    try {
      var session = await createSession();
      List<CFPaymentModes> components = <CFPaymentModes>[];
      // If you want to set paument mode to be shown
// to customer
      var paymentComponent =
          CFPaymentComponentBuilder()
        .setComponents(components)
        .build();
      // We will set theme of checkout session page like
        //fonts, color
      var theme = CFThemeBuilder()
          .setNavigationBarBackgroundColorColor("#FF0000")
          .setPrimaryFont("Menlo")
          .setSecondaryFont("Futura")
          .build();
      // Create checkout with all the settings
//we have set earlier
      var cfDropCheckoutPayment =
     CFDropCheckoutPaymentBuilder()
          .setSession(session!)
          .setPaymentComponent(paymentComponent)
          .setTheme(theme)
          .build();
      // Launching the payment page

      cfPaymentGatewayService.doPayment(cfDropCheckoutPayment);
    } on CFException catch (e) {
      print(e.message);
    }
  }


}

createSessionID(String orderID) async {
  var headers = {
    'Content-Type': 'application/json',
    'x-client-id': "Your app id of cashfree account" ?? "",
    'x-client-secret': "your app secret of cashfree account" ?? "",
    'x-api-version': '2022-09-01',
    // This is latest version for API
    'x-request-id': 'fluterwings'
  };
  print(headers);
  var request =
      http.Request('POST',
Uri.parse('https://sandbox.cashfree.com/pg/orders'));
  request.body = json.encode({
    "order_amount": 1,
// Order Amount in Rupees
    "order_id": orderID,
// OrderiD created by you it must be unique
    "order_currency": "INR",
// Currency of order like INR,USD
    "customer_details": {
      "customer_id": "customer_id",
// Customer id
      "customer_name": "customer_name",
// Name of customer
      "customer_email": "customer_email@gmail.com",
// Email id of customer
      "customer_phone": "+91 customer_mobile_number"
// Phone Number of customer
    },
    "order_meta": {"notify_url": "https://test.cashfree.com"},
    "order_note": "some order note here"
// If you want to store something extra
  });
  request.headers.addAll(headers);

  http.StreamedResponse response = await request.send();

  if (response.statusCode == 200) {
    // If All the details is correct it will return the
    // response and you can get sessionid for checkout
    return jsonDecode(await response.stream.bytesToString());
  } else {
    print(await response.stream.bytesToString());
    print(response.reasonPhrase);
  }
}

💘 Constructors & Destructors in C++ – Jab GF-BF Ke Life Me Entry Aur Breakup Hota 💔🥹

Constructors & Destructors in C++ – GF-BF Format 💡 "Constructor tab call hota jab relationship start hoyi ...