Home Blog Page 5

Understanding JavaScript’s this Keyword with call() Method

0
This keyword in javascript, call() method example.
This keyword in javascript, call() method example.

Hi Guy’s Welcome to Proto Coders Point, In this article let’s understand 'this' keyword in JavaScript and how it plays an important role in JavaScript.

The 'this' keyword is the context in which function it is defined. It is dynamically refers to object that is currently executing the function.

For better understanding let’s refer below code and learn how this keyword context works and how to make use of call() method in JavaScript that allows borrowing methods from one object to another.

Source Code

let obj1 = {
    firstName: "Rajat",
    lastName: "Palankar",
    fullName : function(){
        console.log(this.firstName + " " + this.lastName);
    }
}

let obj2 = {
    firstName: "Suraj",
    lastName: "Somanche",
}

obj1.fullName(); //"Rajat Palankar"

obj1.fullName.call(obj2); // "Suraj Somnache"

In Above JS Snippet Code, we have two objects, named obj1 and obj2, each of this object containing key/Value pair properties firstName and lastName. With this obj1 has an additional method called fullName which simply logs the full name by concatenating firstName and lastName.

Now, let’s check out how the this keyword operates in the context within this fullName method.

When fullName() is called on obj1 by doing something like: obj1.fullName(), here this context refers to the obj1 object itself. Thus, this.firstName will return us “Rajat” and this.lastName will return us “Palankar”, and concat it and print “Rajat Palankar” on screen.

But what if we want to reuse the fullName method that is defined in obj1 but this context should point to obj2 object? This is when we can make use of call() method in javascript.

The call() method allows us to invoke a function with a specific this context. Here’s how it works:

obj.fullName.call(obj2);

The line, obj.fullName refers to the fullName method of obj, and call(obj2) is used to invoke obj1 with obj2 as it’s this context. So, Now this context is refering to obj, In this way now, this.firstName inside the fullName function of obj1 is now refers to obj2.firstName and this.lastName refers to obj2.lastName. Consequently, “Suraj Somanche” is logged to the console.

Android Studio system requirements for laptop or PC (New)

0
Android Studio system requirements
Android Studio system requirements

Hi Guy’s Welcome to Proto Coders Point. In this Article let’s check System requirement to use Android Studio for building Mobile Applications.

As you know that Android Studio is most popular IDE developed by JetBrains & Google, Which was specially built for Developing Android Application but now is days is been used in all field like Mobile Application development, Desktop Application or Single Codebase application development using Flutter.

Android Studio is free to use in all the Operating System Like Windows, macOS, Linux and Chrome OS.

Below are System Requirements to run Android Studio Smoothly.

Windows System Requirement for Android Studio

Minimum system requirements:

  • OS: Windows 8/10/11 (64-bit)
  • CPU: 2nd generation Intel CPU (Sandy Bridge) or newer, AMD CPU with support for a Windows Hypervisor
  • Memory: 8 GB RAM
  • Free storage: 8 GB
  • Screen resolution: 1280 x 800

Recommended system requirements:

  • OS: Windows 10/11 64-bit
  • CPU: Intel Core i5-8400 3.0 GHz or better
  • Memory: 16 GB RAM
  • Free storage: 30 GB (SSD is strongly recommended)
  • Screen resolution: 1920 x 1080

MacOS System Requirement for Android Studio

Minimum system requirements:

  • OS: macOS 10.14 (Mojave) or newer
  • CPU: ARM-based chips, or 2nd generation Intel Core or newer with support for Hypervisor.Framework
  • Memory: 8 GB RAM
  • Free storage: 8 GB
  • Screen resolution: 1280 x 800

Recommended specifications:

  • OS: macOS 10.15 (Catalina)
  • CPU: Intel Core i5-8400 3.0 GHz or better
  • Memory: 8 GB RAM
  • Free storage: 30 GB (SSD is strongly recommended)
  • Screen resolution: 1920 x 1080

Linux System Requirement for Android Studio

Minimum system requirements:

  • OS: Any 64-bit Linux distribution that supports Gnome, KDE, or Unity DE
  • CPU: x86_64 CPU architecture; 2nd generation Intel Core or newer, or AMD processor with support for AMD Virtualization (AMD-V) and SSSE3
  • Memory: 8 GB RAM
  • Free storage: 8 GB
  • Screen resolution: 1280 x 800
  • GNU C Library (glibc) 2.19 or later

Recommend system requirements:

  • OS: Any 64-bit Linux distribution that supports Gnome, KDE, or Unity DE
  • CPU: Intel Core i5-8400 or better
  • Memory: 8 GB
  • Free storage: 20 GB SSD
  • Free resolution: 1920 x 1080
  • GNU C Library (glibc) 2.19 or later

Chrome OS System Requirement for Android Studio

Minimum system requirements:

  • CPU: Intel i5 or higher (U series or higher) recommended
  • Memory: 8 GB
  • Free storage: 8 GB
  • Screen resolution: 1280 x 800

Android Studio system requirements – Conclusion

When you start Android Studio the CPU power is used the max and if your CPU is less then i3 process it may get utilized fully and can get overloaded. Therefore, It is recommended to use at least Intel Core i5-8400 or Higher for smooth running of android studio and mobile device emulator. For better smooth experience I suggest you to install android studio in SSD.

Multiple Listview in Flutter

0
multiple listview in flutter
multiple listview in flutter

Hi Guy’s Welcome to Proto Coders Point. In this Flutter Tutorial will learn How to display Multiple ListViews in Flutter in a single screen where the user can interact with both the list at once.

Video Tutorial

Source Code

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final fruits = List.generate(100, (index) => "Fruit $index");
  final veg = List.generate(100, (index) => "Veg $index");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: MediaQuery.of(context).size.width,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
            child: Text(
              "Fruits",
              style: TextStyle(fontSize: 18),
            ),
            color: Colors.blueAccent,
          ),
          Expanded(
            child: ListView.builder(
                itemCount: fruits.length,
                itemBuilder: (context, index) {
                  return Container(
                    child: ListTile(
                      title: Text(fruits[index]),
                    ),
                  );
                }),
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
            child: Text(
              "Veg",
              style: TextStyle(fontSize: 18, color: Colors.white),
            ),
            color: Colors.black,
          ),
          Expanded(
            child: ListView.builder(
                itemCount: veg.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(veg[index]),
                  );
                }),
          )
        ],
      ),
    );
  }
}

Code Explanation

I have generated a list of data that I want to display in listview.

final fruits = List.generate(100, (index) => "Fruit $index");
final veg = List.generate(100, (index) => "Veg $index");

In above snippet code, I have created 2 dummy list of data by using List.generator and I want to display both the list of data into once screen itself, so that user can easily interact with both of then on single screen.

Then, To display multiple widgets we make use of Column widget to arrange it’s children vertically. In Column widget we place 2 section: one to display fruits and another to display list of vegetables for this we make use of ListView.builder.

Each ListView.builder is configured with an itemCount property to determine the number of items in the list.

The itemBuilder property defines a callback function that returns a widget for each item in the list.

In the provided code, ListTile widgets are used as list items, displaying text based on the content of fruits and veg lists.

Event Loops in JavaScript with code example | NodeJS

0
What is Event Loop With Code Example
What is Event Loop With Code Example

Hi Guy’s Welcome to Proto Coders Point. In this article let’s learn about Event Loop in JavaScript with code example.

What is Event Loop?

As you know that JavaScript works on a single threads, It can execute only one task at a time, But when building application using JS at backend, We can execute multiple tasks at a same time, like instance, Listening for events, and timeout etc.

To handle multiple event or calculation JavaScript make use of event loop. It is a concurrency model that has four major component. i.e. Call Stack, Web API’s, Task Queue and Micro Task Queue.

javascript event loop

Component’s of JavaScript Event Loops

1. Call Stack: A Stack Data Structure (LIFO) Last In First Out Stack Model, that is used for keeping track of current execution function calls.

2. Web API’s: When any API event like setTimeout or DOM manipulation function gets into the call Stack, They are moved to separate bucket known as Web API’s. Once the API execution is completed is is poped from the Call Stack so that Call Stack can execute next.

3. Task Queue: When the setTimeout() delay finishes, The Web API moves the timeout to the Task Queue. Then the Task Queue will wait for the Call Stack to get empty. Once it gets empty, It will remove the first task from the queue & moves it on the Call Stack to execute that code.

4. Micro Task Queue: This is Another Queueing system, Micro Task Queue has Higher Priority than Task Queue but it holds promises instead of Web API’s. It Follow the same principle of pushing task into Call Stack when Call Stack is empty.

Event loop in javascript example or In NodeJS

Here is a example on event loop in JavaScript:

Code:

// Define a function that simulates an asynchronous task

function simulateAsyncTask(taskName, duration) {
  console.log(`${taskName} started`);
  setTimeout(() => {
    console.log(`${taskName} completed after ${duration} milliseconds`);
  }, duration);
}

// Simulate two asynchronous tasks

simulateAsyncTask("Task 1", 2000);
simulateAsyncTask("Task 2", 1000);

console.log("Main program continues executing...");

Event Loop Code Explanation:

We have created a function by name simulateAsyncTask which accepts two parameters: taskName (a string representing the name of the task) and duration (the duration of the task in milliseconds).

Then simulateAsyncTask, we firstly print/log that the task has started, then use setTimeout to simulate an asynchronous operation and then pass the timeout duration to complete it. Once the timeout elapses, we print/ log that the task has completed.

We simulate two asynchronous tasks: “Task 1” with a duration of 2000 milliseconds i.e. 2 seconds & “Task 2” with a duration of 1000 milliseconds i.e. 1 second.

After starting the asynchronous tasks, we have simply made use of console.log that print msg on the screen “Main program continues executing…”.

When you run this code, you’ll notice that “Main program continues executing…” is logged immediately, before the asynchronous tasks complete. This demonstrates the non-blocking nature of asynchronous JavaScript code and the event loop in action. The event loop manages the execution of asynchronous tasks, allowing the main program to continue executing while waiting for tasks to complete.

Types of Functions in JavaScript with Example

0
Types of Functions in JavaScript
Types of Functions in JavaScript

As you all know JavaScript is been widely used now a days in all the fields, May be it’s FrontEnd or BackEnd as it’s is a dynamic programming language and can be easily be used to developer software that can be scalable in future.

In this JavaScript Article let’s check in how many types we can create a function in JS..

Types of Functions in JavaScript

To keep knowledge of different ways to create a functions in JavaScript is very much important for any developer to write clean, efficient and easily to read and maintain the code. Here are 6 Ways to create function in JS.

  • Named Functions.
  • Anonymous Functions.
  • Arrow Functions.
  • Immediately Invoked Functions Expressions (IIFE).
  • Higher Order Functions.
  • Constructor Functions.

Let’s Check each of them and it’s Syntax

1. Named Function

Named function in JS are defined by using function keyword, then comes name of the function. This Func can be declared anywhere in the code and are always hoisted to the top of the scope at the time of execution.

Example:

function greet(name) {
    return `Hello, ${name}!`;
}

2. Anonymous Functions

As the name itself define it has no name been given.

Example:

const add = function(x, y) {
    return x + y;
};

You might be wondering, A function is been created (without name) and simply assigned to a variable which holds the complete function structure, Then how it can be anonymous function as the variable itself can be function name right?

Here in add variable we have simply assigned a anonymous function. The Function itself does not have a name, but it just defined as part of the assignment to the add variable.

Usually Anonymous function are commonly used when we need to use function for temporary reason or as an argument to another function (closures).

Another Function

document.addEventListener('click', function() {
    console.log('Document was clicked!');
});

3. Arrow Functions

In JS Arrow Function was introduced with ECMAScript 6 (ES6), Very helpful to write shorter function or one-lined function.

const functionName = (parameters) => console.log(parameters);

Another example for Arrow Functions

const add = (a, b) => a + b;

Note: Arrow Function don’t have their own this context as they are lack in prototype, and also make it not suitable for defining object constructors.


4. Immediately Invoked Functions Expressions (IIFE)

IIFE are those type of functions that executes immediately where they are defined, No need to separately call to run it.

(function() {
    // Code to be executed immediately
})();

5. Recursive Functions

Recursive functions are those that call itself. Here we need to apply some logic to avoid infinite loop of calling itself. They are commonly used for tasks such as tree traversal, factorial calculation, and solving mathematical problems.

Example:

function factorial(n) {
    if (n === 0) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

6. Generator Functions

This provide a powerful mechanism for asynchronous programming, generator function in javascript are used to control like pausing & resuming execution of a function. In generator function we have yield keyword that enables the creation of iterators.

function* generateSequence() {
    yield 1;
    yield 2;
    yield 3;
}

Example:

function* generateSequence() {
    yield 1;
    yield 2;
    yield 3;
}

const sequence = generateSequence();

console.log(sequence.next()); // Output: { value: 1, done: false }
console.log(sequence.next()); // Output: { value: 2, done: false }
console.log(sequence.next()); // Output: { value: 3, done: false }
console.log(sequence.next()); // Output: { value: undefined, done: true }

In this example, generateSequence is a generator function that yields three values: 1, 2, and 3. When you call generateSequence(), it returns an iterator object. You can then use the iterator’s next() method to iterate over the values yielded by the generator.

Each call to next() returns an object with two properties: value, which contains the yielded value, and done, which indicates whether the generator has finished iterating. When the generator function has yielded all its values, subsequent calls to next() return an object with done set to true and value set to undefined.

Build Chat AI in Flutter using Google Gemini AI API – Source Code

0
build Ai Chat bot in flutter using google gemini ai API
build Ai Chat bot in flutter using google gemini ai API

Hi Guy’s Welcome to Proto Coders Point, In this Flutter Tutorial Will 🚀 Learn to build a Flutter AI Chatbot app using Google’s Gemini AI API, For this we gonna make use of the flutter pacakge named “google_generative_ai“. Explore the magic of gemini ai as we create intelligent chat features in our flutter application . Elevate your Flutter skills and enjoy a step-by-step guide to build an AI-powered chat app! 🤖📱.

Flutter Google Generative AI

To build Flutter AI-Powered chatbot we will make use of a package called “google_generative_ai”, and to communicate with google gemini ai we need a gemini API Key.

Check out the complete video tutorial on how to build AI Chatbot in flutter using gemini AI

How to get Gemini AI API key

Simply check out the above video to get gemini AI API key else click on button below:

Build ChatBot Flutter App

1. Create or open a Flutter project

2. Add dependencies
Open pubspec.yaml file from your flutter project and under depencencies section add below dependencies

dependencies:
  google_generative_ai:  
  intl:

google generative ai: used to communicate with gemini AI.

intl: used for DataTime Formating.


Basic Information on how to use google generative ai package (code explanation)

This is Snippet Code- Not Complete Code- Find Complete code below with UI design Chat App

final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);
final content = [Content.text(message)];
final response = await model.generateContent(content);

This above snippet code initializes a GenerativeModel object with the specified model (‘gemini-pro’) and API key. Then, it prepares the content to be sent to the AI model (Basically a Text/prompt message), which consists of a list containing a single text content (message). Finally, it sends this content to the Gemini AI model and awaits the response, which will contain the AI-generated content based on the input message user provide.

Complete Source Code – Building an AI Chatbot in Flutter Using Google’s Generative AI Package

Result/Output of below Code

flutter Ai ChatBot using Google Gemini AI

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_generative_ai/google_generative_ai.dart';
import 'package:intl/intl.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const ChatScreen(),
    );
  }
}

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

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  TextEditingController _userInput =TextEditingController();

  static const apiKey = "<Replace You Gemini API Key Here>";

  final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);

  final List<Message> _messages = [];

  Future<void> sendMessage() async{
    final message = _userInput.text;

    setState(() {
      _messages.add(Message(isUser: true, message: message, date: DateTime.now()));
    });

    final content = [Content.text(message)];
    final response = await model.generateContent(content);


    setState(() {
      _messages.add(Message(isUser: false, message: response.text?? "", date: DateTime.now()));
    });

  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
              colorFilter: new ColorFilter.mode(Colors.black.withOpacity(0.8), BlendMode.dstATop),
            image: NetworkImage('https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigDbiBM6I5Fx1Jbz-hj_mqL_KtAPlv9UsQwpthZIfFLjL-hvCmst09I-RbQsbVt5Z0QzYI_Xj1l8vkS8JrP6eUlgK89GJzbb_P-BwLhVP13PalBm8ga1hbW5pVx8bswNWCjqZj2XxTFvwQ__u4ytDKvfFi5I2W9MDtH3wFXxww19EVYkN8IzIDJLh_aw/s1920/space-soldier-ai-wallpaper-4k.webp'),
            fit: BoxFit.cover
          )
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Expanded(
                child: ListView.builder(itemCount:_messages.length,itemBuilder: (context,index){
                  final message = _messages[index];
                  return Messages(isUser: message.isUser, message: message.message, date: DateFormat('HH:mm').format(message.date));
                })
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                children: [
                  Expanded(
                    flex: 15,
                    child: TextFormField(
                      style: TextStyle(color: Colors.white),
                      controller: _userInput,
                      decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(15),
                        ),
                        label: Text('Enter Your Message')
                      ),
                    ),
                  ),
                  Spacer(),
                  IconButton(
                    padding: EdgeInsets.all(12),
                      iconSize: 30,
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(Colors.black),
                        foregroundColor: MaterialStateProperty.all(Colors.white),
                        shape: MaterialStateProperty.all(CircleBorder())
                      ),
                      onPressed: (){
                      sendMessage();
                      },
                      icon: Icon(Icons.send))
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

class Message{
  final bool isUser;
  final String message;
  final DateTime date;

  Message({ required this.isUser, required this.message, required this.date});
}

class Messages extends StatelessWidget {

  final bool isUser;
  final String message;
  final String date;

  const Messages(
      {
        super.key,
        required this.isUser,
        required this.message,
        required this.date
      });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(15),
      margin: EdgeInsets.symmetric(vertical: 15).copyWith(
        left: isUser ? 100:10,
        right: isUser ? 10: 100
      ),
      decoration: BoxDecoration(
        color: isUser ? Colors.blueAccent : Colors.grey.shade400,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          bottomLeft: isUser ? Radius.circular(10): Radius.zero,
          topRight: Radius.circular(10),
          bottomRight: isUser ? Radius.zero : Radius.circular(10)
        )
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            message,
            style: TextStyle(fontSize: 16,color: isUser ? Colors.white: Colors.black),
          ),
          Text(
            date,
            style: TextStyle(fontSize: 10,color: isUser ? Colors.white: Colors.black,),
          )
        ],
      ),
    );
  }
}