Problem with using HTML form data in javascript functions

Recently I have been trying to change my code that took one HTML user input and used it in a javascript function. To do this I put the input into a query string and that worked fine. Then I tried to add another input. This is currently the form part of my code.

<form onsubmit="bazaartable()" class="pb-1">
    <div>
        <label>Please enter your tax rate here <i>(If not entered will use 1%)</i>:</label>
        <input type="text" id="taxRateForm" class="border border-cyan-500 rounded"/>
    </div>

    <div>
        <label><i>Enter unique amount here if needed</i>:</label>
        <input type="text" id="amountForm" class="border border-cyan-500 rounded"/>
    </div>
    
    <input type="submit" class="bg-cyan-500 py-1 px-1 rounded"/>
</form>

This is some of my javascript code including the function bazaartable.

<script>
    function takevalue1(){
        var taxRate = document.getElementById("taxRateForm").value;
        if (taxRate < 1){
                taxRate = 1
        }
        return taxRate
    }

    function takevalue2(){
        var amount = document.getElementById("amountForm").value;
        return amount
    }
    
    console.log(takevalue1())
    console.log(takevalue2())

    function bazaartable(){
    getbazaar = () => new Promise(a => getbazaar.data && !a(getbazaar.data) || fetch("https://api.hypixel.net/skyblock/bazaar").then(x => a(getbazaar.data = x.json())));
    document.getElementById("bazaar").innerHTML = arrayToTable([["Item Name", "Price x1 -0.1 Including Tax", "Price x64 -0.1 Including Tax", "x" + takevalue2()]], '<div class="row">{{content}}</div>', '<div class="column">{{content}}</div>');
    getbazaar().then(makeArray).then(x => arrayToTable(x, '<div class="row">{{content}}</div>', '<div class="column" title="{{content}}">{{content}}</div>')).then(x => document.getElementById("bazaar").innerHTML += x);
    }

    var iLikeThese = ["ENCHANTED_SNOW_BLOCK", "ENCHANTED_POTATO", "ENCHANTED_CARROT", "ENCHANTED_CLAY_BALL", "ENCHANTED_DIAMOND", "ENCHANTED_REDSTONE_BLOCK", "PACKED_ICE", "ICE"];
    
    function makeArray(data) {
        var arr = [];
        for (var i in data.products) {
            if (!iLikeThese.includes(i)) continue;
            var price = null;
            try {
                price = data.products[i].buy_summary[0].pricePerUnit
                price = price -= .1
                priceAfterTax = (price - (takevalue1()/100 * price))
            } catch (e) {}
            arr.push([i.replace(/_/g, " ").toLowerCase(), priceAfterTax.toFixed(1), (priceAfterTax*64).toFixed(1), (priceAfterTax*takevalue2()).toFixed(1)]);
        }
        return arr.sort((a, b) => a[0] > b[0] ? 1 : -1);
    }

    function arrayToTable(arr, row, column) {
        var result = "",
            substr = "";
        for (var i = 0; i < arr.length; i++) {
            substr = "";
            for (var j = 0; j < arr[i].length; j++) {
                substr += column.replace(/{{content}}/g, arr[i][j]);
            }
            result += row.replace(/{{content}}/g, substr);
        }
        return result;
    }
</script>

I have tried making takevalue1&2 return numbers but that and that works. The only thing that I can think of is that clicking the button clears the inputs before the function can read the values. If anyone can help please reply!

Foreach value insert to array

I have a Foreach data connected to a button.
I want to insert this foreach data into an array called myArray every time I click the button.
When I do myArray.push() , the data is added on top of each other.
3 data on the first click, 6 data on the second, 9 data on the 3rd…
However, I want that data to be updated, not pushed, so I want always 3 data, I just want their values to change, how can I do this?
Thanks.

// Foreach data
{
  "_id": "b94a22f5-acea-c649-d203-bdaa533c35b8",
  "productName": "Cookies",
  "productImage": "image://v1/6318fc_4f5a4c323cf74b21aaa61ddba1e924fb~mv2.jpg/file.jpg#originWidth=1050&originHeight=1050",
  "quantity": 4
}
{
  "_id": "dd7247dc-4f5f-a7fe-57df-20dce972fdc6",
  "productName": "Cake",
  "productImage": "image://v1/6318fc_c9a8011220064ddcb0bed049d1f6883d~mv2.jpg/file.jpg#originWidth=1200&originHeight=1800",
  "quantity": 3
}
{
  "_id": "ce5cae3b-db5a-623e-8c93-fec1c40c295d",
  "productName": "Coffee",
  "productImage": "image://v1/6318fc_4d19f3b393d94aa1aac03ab99b3abd8d~mv2.png/file.png#originWidth=833&originHeight=942",
  "quantity": 1
}


// I want it to be like this
console.log(myArray)
// output
// [
//   {
//   "_id": "b94a22f5-acea-c649-d203-bdaa533c35b8",
//   "productName": "Cookies",
//   "productImage": "image://v1/6318fc_4f5a4c323cf74b21aaa61ddba1e924fb~mv2.jpg/file.jpg#originWidth=1050&originHeight=1050",
//   "quantity": 4
// },
// {
//   "_id": "dd7247dc-4f5f-a7fe-57df-20dce972fdc6",
//   "productName": "Cake",
//   "productImage": "image://v1/6318fc_c9a8011220064ddcb0bed049d1f6883d~mv2.jpg/file.jpg#originWidth=1200&originHeight=1800",
//   "quantity": 3
// },
// {
//   "_id": "ce5cae3b-db5a-623e-8c93-fec1c40c295d",
//   "productName": "Coffee",
//   "productImage": "image://v1/6318fc_4d19f3b393d94aa1aac03ab99b3abd8d~mv2.png/file.png#originWidth=833&originHeight=942",
//   "quantity": 1
// }
// ]

Can not excess the value of a variable outside the class

i have this code where it will show the temperature of a place using Accuweather API. right now I have hardcoded newdelhi into it to find the weather condition of that place.but I want to know the weather by using the form. i am right know testing it with first name input form and trying to send that value in the location function. but I can’t use the input given by the user and use it outside the class. need help. i am new in react and appreciate if someone could help me with it. thank you

import React ,{useState,useEffect,state}from 'react';
import './App.css';
const apikey='zVp5GoY9fbwt8h4u5CvcWwneD1emnMMD';

const getcity = async(city) => {
    const base = 'http://dataservice.accuweather.com/locations/v1/cities/search';
    const query = `?apikey=${apikey}&q=${city}`;
  
    const response = await fetch(base + query);
    const data = await response.json();
  
    return data[0];
  }

  getcity('New Delhi')
  .then(data => {
    return getweather(data.Key);
  }).then(data =>{
    console.log(data);
  })
  .catch(err =>console.error(err));

  const getweather = async(id)=>{
  
    const base= 'http://dataservice.accuweather.com/currentconditions/v1/';
    const query =`${id}?apikey=${apikey}`;
  
    const response = await fetch(base + query)
    const data = await response.json();
  
    return data[0];
  }
  let newval = "initial value";
  console.log(newval)

export default class CustomerForm extends React.Component {

  
    
    
  constructor(props) {
    super(props);
    

    this.state = {
      customer: {
        firstName: props.firstName,
        lastName: props.lastName,
        status: props.status,
        
      }
    } 
  }

  handleFirstNameChanged(event) {
    var customer        = this.state.customer;
    customer.firstName  = event.target.value;

    this.setState({ customer: customer });
  }

  handleLastNameChanged(event) {
    var customer      = this.state.customer;
    customer.lastName = event.target.value;

    this.setState({ customer: customer });
  }

  handleStatusChanged(event) {
    var customer    = this.state.customer;
    customer.status = event.target.value;
    this.setState({ customer: customer });
  }
  
  
  handleButtonClicked() {
    console.log(this.state.customer);
    newval=this.state.customer.firstName;
    console.log(newval);
  }
  
  render() {
    return (
      <div>
        <label>
          First Name: 
        </label>
        <input type="text" value={this.state.customer.firstName} onChange={this.handleFirstNameChanged.bind(this)}/>
        <br/>
        <label>
          Last Name:
        </label>
        <input type="text" value={this.state.customer.lastName} onChange={this.handleLastNameChanged.bind(this)}/>
        <br/>
        <label>
          Status:
        </label>
        <select value={this.state.customer.status} onChange={this.handleStatusChanged.bind(this)}>
          <option value="PENDING">
            Pending
          </option>
          <option value="APPROVED">
            Approved
          </option>
        </select>
        <hr/>
        <button onClick={this.handleButtonClicked.bind(this)}>
          Save Record
        </button>
      </div>
    );
  }
}

Sending data from a Javascript program to a Python program and vice versa

I’m working on a project where data gathered from a Javascript program can be treated in a python program since many libraries in python are absent in Javascript. I’m currently trying to use Ajax to send the data between the .js file and the .py file

    $.ajax({
      type: "POST",
      url: "/Users/ryancheng/Desktop/coding/dashathon2021/dasha-app/webscrape.py",
      data: {param:restResult.data.features},
      success: function(response){
        output = response;
        alert(output);
      }
    }).done(function(data){
      console.log(data);
      alert(data);
    })

However I get the error ReferenceError: $ is not defined. Any help would be much appreciated. If there is any other method to send files back and forth that I am not aware of, please let me know.

how to insert array of data per column in MySQL?

I have arrays stacked in 1 array and I would like to insert each array per column in MySQL.
I have reached to insert all data in arrays to 1 column, but I want to insert an array per column.
Please see the screenshot and code below.

Image of array stack

con.connect(async(err)=>{
  const x = await getStock()
  if(err){
      console.log(err);
      return err;
  }else{
      console.log("DB ok");
  }
  console.log("connected");
  x.filter(item=>item===undefined?false:true).map(item=>item.forEach(item=>{
    const sql ="INSERT INTO test (testCol1) VALUES ?";
    const values=[
      [item]
    ];
    con.query(sql,[values],(err,result)=>{
      if(err)throw err;
      console.log("this have been recorded"+result);
    });
  }));
});

Javascrit .createTextNode output is giving errors

I created a website where it tells you your age. I use document.createTextNode to store the output but the output is not working properly. Here is the output code

var h1 = document.createElement("p");
h1.setAttribute("id", "mainText")
var mainText = document.createTextNode("You are ", ageYears, " years, ", ageMonths, " 
months and ", ageDays, " days old.");
h1.appendChild(mainText);
document.getElementById("new-age").appendChild(h1);

When I run my code, it only outputs the first part, “You are”. Is there any way to output the entire message.

when running npm run serve on lunix it’s not working

[email protected] serve
vue-cli-service serve

ERROR TypeError: Cannot read properties of undefined (reading ‘version’)
TypeError: Cannot read properties of undefined (reading ‘version’)
at module.exports (/home/compumart/Public/Front-End/app-zero/node_modules/@vue/cli-plugin-eslint/index.js:20:27)
at /home/compumart/Public/Front-End/app-zero/node_modules/@vue/cli-service/lib/Service.js:78:7
at Array.forEach ()
at Service.init (/home/compumart/Public/Front-End/app-zero/node_modules/@vue/cli-service/lib/Service.js:76:18)
at Service.run (/home/compumart/Public/Front-End/app-zero/node_modules/@vue/cli-service/lib/Service.js:215:10)
at Object. (/home/compumart/Public/Front-End/app-zero/node_modules/@vue/cli-service/bin/vue-cli-service.js:36:9)
at Module._compile (node:internal/modules/cjs/loader:1095:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10)SEMBLY’ ‘-DV8_ALLOCATION_FOLDING’ ‘-DV8_ALLOCATION_SITE_TRACKING’ ‘-DV8_ADVANCED_BIGINT_ALGORITHMS’ ‘-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC’ ‘-DUCONFIG_NO_SERVICE=1’ ‘-DU_ENABLE_DYLOAD=0’ ‘-DU_STATIC_IMPLEMENTATION=1’ ‘-DU_HAVE_STD_STRING=1’ ‘-DUCONFIG_NO_BREAK_ITERATION=0’ -I../deps/v8 -I.

Form POST request, not working. Undefined in Server (HTML,JS,EXPRESS,NODE,MONGODB)

Im working in an application with a front and a back end, my back end written in nodejs, using express, multer and mongoose, is working pretty fine when i send data through postman, but as soon as i try the same request in my client made with html,css and vanilla javascript, it doesnt work, it gives me the following error:

TypeError: Cannot read property ‘path’ of undefined (which is pointing towards my network file that manages connections for a specific entity).

Despite the error mentioned above, i’ve been trying to send a file and a string from the form in html to the network file in my node server, but i keep getting the same 2 or so errors in terminal.

Here is some code so you can understand better.

server.js (main entry point)

const express = require('express');
const app = express();
const server = require('http').Server(app);
const path = require('path');

const cors = require('cors');
const bodyParser = require('body-parser');
const db = require('./db');
const router = require('./network/routes');
const config = require('./config');

db(config.dbUrl);
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(`${config.publicRoute}`, express.static(path.join(__dirname, 'public')));
server.listen(config.port, function() {});
console.log(`Application listen on ${config.host}${config.port}`);
router(app);

network.js (file that manages connections for “banner” entity)

const express = require('express');
const multer = require('multer');
const router = express.Router();
const response = require('../../network/response');
const controller = require('./controller');
const path = require('path');
const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, path.join(__dirname, '../../public/files'))
    },
    filename: function(req, file, cb) {
        cb(null, path.extname(file.originalname))
    }
})
const upload = multer({ storage: storage })

router.post('/', upload.single('file'), function(req, res) {

    console.log(req.body);
    controller.addBanner(req.body.name, req.file, req.file.path)
        .then((fullMessage) => {
            response.success(req, res, fullMessage, 201);
        })
        .catch(e => {
            response.error(req, res, 'Unexpected error', "Simulated Error", 400, e);
        });
});

router.get('/', function(req, res) {
    controller.getBanners()
        .then((banners) => {
            response.success(req, res, banners, 200);
        })
        .catch(e => {
            response.error(req, res, 'Internal Error', 500, e);
        })
});

router.delete('/:id', function(req, res) {
    controller.deleteBanner(req.params.id)
        .then(() => {
            response.success(req, res, `Imagen con id: ${req.params.id} ,eliminada`, 200);
        })
        .catch(e => {
            response.error(req, res, 'Internal Error', 500, e);
        })
});

module.exports = router;

panel.html (where the form that supposedly sends the post request lies)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- <meta http-equiv="Content-Security-Policy" content="default-src https://cdn.example.net; child-src 'none'; object-src 'none'"> -->
    <link rel="stylesheet" type="text/css" href="css/panel-style.css">
    <script defer src="panel-script.js"></script>
    <title>Panel de Control</title>
</head>

<body>
    <header>
        <img src="assets/mrvapeslogo.png" alt="mrvapes logo">
        <a href="index.html"></a>
    </header>
    <section>
        <form accept-charset="UTF-8" enctype="multipart/form-data" action="../components/banner/network.js" autocomplete="off" method="GET" target="_blank">
            <label for="user">Banners Activos</label><br/>
            <ul class="files-container">

            </ul>
        </form>
        <form accept-charset="UTF-8" enctype="multipart/form-data" action="http://localhost:3000/banner" autocomplete="off" method="POST" target="_blank">
            <div class="container">
                <div class="button-wrap">
                    <!-- <label class="button" for="upload">Subir</label> -->
                    <input type="text" id="name" placeholder="Nombre de Archivo" value="" name="name" required>
                    <input id="image" value="Subir" placeholder="Subir Archivo" type="file" required>
                    <button id="upload" name="send-post--request" value="post-request" type="submit">Enviar</button>
                    <!-- <input id="upload" type=" submit " value="Enviar " onclick="submit() "> -->
                </div>
            </div>
        </form>
    </section>
</body>

panel-script.js (client-side file that manages the logic for the http request)

const upload = document.getElementById("upload");
const image = document.getElementById("image");
const title = document.getElementById("name");

upload.addEventListener("click", (e) => {
    console.log('im in bro');
    e.preventDefault();
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            alert(xhr.response);
        }
    }
    xhr.open("POST", 'http://localhost:3000/banner', true);
    //xhr.setRequestHeader("Accept", "multipart/form-data");
    //xhr.setRequestHeader('Content-Type', 'multipart/form-data');
    var fileSent = {
        "name": title,
        "file": image
    };
    console.log(fileSent);
    xhr.send(fileSent);
    alert('Subida exitosa!');
})


function retrieve() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            alert(xhr.response);
        }
    }
    xhr.open('get', 'http://localhost:3000/banner', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.send();
}

I’m all ears towards your suggestions, thanks in advance fellow developers.

Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’) at (index):72

let searchBtn = document.querySelector ( '#Search-btn');

let searchBar = document.querySelector ( ‘.search-bar-container’);

searchBtn.addEventListener(‘click’, () =>{

searchBtn.classlist.toggle('fa-times');
searchBar.classList.toggle('active');

});

let searchBtn = document.querySelector ( '#Search-btn');
let searchBar = document.querySelector ( '.search-bar-container');

searchBtn.addEventListener('click', () =>{

    searchBtn.classlist.toggle('fa-times');
    searchBar.classList.toggle('active');
});
@import url('https://fonts.googleapis.com/css2?family=Nunito:wght@200;300;400;600;700&display=swap');

:root {
    --orange:#ffa500;
    
}

*{
    font-family: 'Nunito', sans-serif;
    margin: 0; padding: 0;
    box-sizing: border-box;
    text-transform: capitalize;
    outline: none; border: none;
    transition: all .2s linear;
    text-decoration: none;
    
}

*::selection{
    background: var(--orange);
    color: #fff;
}

html{
    font-size: 62.5%;
    overflow-x: hidden;
    scroll-padding-top: 6rem;
    scroll-behavior: smooth;
}

header{
    position: fixed;
    top: 0; left: 0; right: 0;
    background: #333;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 2rem 9%;
}

header .logo {
    font-size: 2rem;
    font-weight: bolder;
    color: #fff;
    text-transform: uppercase;
}

header .logo span {
    color: var(--orange);
}

header .navbar a{
    font-size: 2rem;
    color: #fff;
    margin:0 .8rem;
}

header .navbar a:hover{
    color: var(--orange);
}

header .icons i{
    font-size: 2.5rem;
    color:#fff;
    cursor: pointer;
    margin-right: 2rem;
}

header .icons i:hover{
    color: var(--orange);
}

header .search-bar-container{
    position: absolute;
    top: 100%; left: 0; right: 0;
    padding: 1.5rem 2rem;
    background: #333;
    border-top: .1rem solid rgba(225, 225, 225, .2);
    display: flex;
    align-items: center;
    z-index: 1001;
    clip-path: polygon(0 0, 100% 0, 0 0);
}

header .search-bar-container.active{
    clip-path: polygon(0 0, 100% 0, 0 0);
}

#search-bar {

    width: 100%;
    padding: 1rem;
    text-transform: none;
    color: #333;
    font-size: 1.7rem;
    border-radius: 100rem;
}

header .search-bar-container label{
    color: #fff;
    cursor: pointer;
    font-size: 3rem;
    margin-left: 1.5rem;
}

header .search-bar-container label:hover {
    color: var(--orange);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Travel Agency</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    
<header>
    <a href="#" class="logo"> <span>T</span>ravel</a>

    <nav class="navbar">
        <a href="#home">home</a>
        <a href="#book">book</a>
        <a href="#package">package</a>
        <a href="#services">services</a>
        <a href="#review">review</a>
        <a href="#contact">contact</a>
    </nav>

    <div class="icons">
        <i class="fa fa-search" id="search-btn"></i>
        <i class="fa fa-user" id="login-btn"></i>
    </div>

    <form action="" class="search-bar-container">
        <input type="search" id="search-bar" placeholder="search here...">
        <label for="search-bar" class="fa fa-search" ></label>
    </form>

</header>

When I try to run my javascript code its give me an error. I do check my code and syntax twice i could not find the error please help me with that.

Using XPath to get an elmement in SVG

I am trying to get an element in an SVG file using XPath. I have tried the following code, but singleNodeValue is null. The doc seems to be correct, so I guess either evaluate() arguments or the XPath is wrong, but I cannot find anything wrong. Why doesn’t it work?

JavaScript

fetch('test.svg')
.then(response => response.text())
.then(data=>{
    const parser = new DOMParser();
    const doc = parser.parseFromString(data, "text/xml");
    console.log(doc);
    const res = doc.evaluate("//symbol[@label='square']", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    console.log(res.singleNodeValue);
})

SVG

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">

    <symbol label ="square">
        <rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
    </symbol>

</svg>

How do i trigger a link with no id via console

I am simply trying to trigger a link with no id via console. I have tried multiple scenarios and none seem to work. It is a link with lots of classes and no id.

$('.videoHolder').find('a.icon-play').trigger('click');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="videoHolder hover">
  <div class="videoDisplay">

    <video class="persistentNativePlayer nativeEmbedPlayerPid" poster="data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%01%00%00%00%01%08%02%00%00%00%90wS%DE%00%00%00%01sRGB%00%AE%CE%1C%E9%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%07tIME%07%DB%0B%0A%17%041%80%9B%E7%F2%00%00%00%19tEXtComment%00Created%20with%20GIMPW%81%0E%17%00%00%00%0CIDAT%08%D7c%60%60%60%00%00%00%04%00%01'4'%0A%00%00%00%00IEND%AEB%60%82"
      id="pid_kaltura_player" kentryid="1_4u0ocu4u" kuiconfid="" kwidgetid="" kpartnerid="" preload="none" width="560" height="395" src="" style="position: absolute; left: 0px; top: 0px;"></video>
    <div class="videoShadow"></div>
    <div class="mwEmbedPlayer" id="kaltura_player" style=""></div>
  </div><a tabindex="-1" href="#" role="button" class="comp largePlayBtn  largePlayBtnBorder icon-play" aria-label="Play clip" data-order="1" data-plugin-name="largePlayBtn" style="display: flex; opacity: 1;">Mylink</a></div>

while clicking local push notification how to navigate and reload a page in flutter

Hi iam new user in flutter app. I need while clicking the notification navigate and reload the page. can you please suggest how to navigate and reload the page while clicking the notification. i have used flutter local push notification as the following example link(https://blog.logrocket.com/implementing-local-notifications-in-flutter/) working fine but while clicking the notication the page does’t navigate and reload.

I have also created secondscreen(this is navigate page) but in this code selectNotification functionality not working. please check below code and give me a solution.

//notification_service.dart
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'secondscreen.dart';

import 'main.dart';

class NotificationService {
  //NotificationService a singleton object
  static final NotificationService _notificationService =
      NotificationService._internal();

  factory NotificationService() {
    return _notificationService;
  }

  NotificationService._internal();

  static const channelId = '123';

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  Future<void> init() async {
    final AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    final IOSInitializationSettings initializationSettingsIOS =
        IOSInitializationSettings(
      requestSoundPermission: false,
      requestBadgePermission: false,
      requestAlertPermission: false,
    );

    final InitializationSettings initializationSettings =
        InitializationSettings(
            android: initializationSettingsAndroid,
            iOS: initializationSettingsIOS,
            macOS: null);

    tz.initializeTimeZones();

    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: selectNotification);
  }

  AndroidNotificationDetails _androidNotificationDetails =
      AndroidNotificationDetails(
    'channel ID',
    'channel name',
    'channel description',
    playSound: true,
    priority: Priority.high,
    importance: Importance.high,
  );

  Future<void> showNotifications() async {
    await flutterLocalNotificationsPlugin.show(
      0,
      "Notification sundar",
      "This is the Notification Body!",
      NotificationDetails(android: _androidNotificationDetails),
    );
  }

  Future<void> scheduleNotifications() async {
    await flutterLocalNotificationsPlugin.zonedSchedule(
        0,
        "Notification Title",
        "This is the Notification Body!",
        tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
        NotificationDetails(android: _androidNotificationDetails),
        androidAllowWhileIdle: true,
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime);
  }

  Future<void> cancelNotifications(int id) async {
    await flutterLocalNotificationsPlugin.cancel(id);
  }

  Future<void> cancelAllNotifications() async {
    await flutterLocalNotificationsPlugin.cancelAll();
  }
}

Future selectNotification(String payload) async {
  //handle your logic here
  print('String');
  if (payload != null) {
    print('sundar');
    BuildContext context;
    Navigator.push(
      context,
      MaterialPageRoute<void>(builder: (context) => SecondScreen()),
    );
  }
}