Home Blog Page 2

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,),
          )
        ],
      ),
    );
  }
}

Check if Array is dominant Array

0
check if the array in dominant array or not
check if the array in dominant array or not

Most asked interview question – Check if the array is a dominant array or not

Problem Statement

You are given an array A of length N . An element X is said to be dominant if the frequency of X in A is strictly greater than the frequency of any other element in the A .
For example, if A=[2,1,4,4,4] then 4 is a dominant element since its frequency is higher than the frequency of any other element in A .
Find if there exists any dominant element in A.

Input Format
The first line of input contains a single integer T — the number of test cases.
Then the test cases follow.
The first line of each test case contains an integer N — the size of the array A .
The second line of each test case contains N space-separated integers denoting the array A.


Output Format
For each test case, output YES if there exists any dominant element in A . Otherwise, output NO.
You may print each character of YES and NO in uppercase or lowercase (for example, yes, yEs, Yes will be considered identical).

Constraints Sample 1:
1 ≤ T ≤ 500
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ N

Sample 1:

Input
4
5
2 2 2 2 2
4
1 2 3 4
4
3 3 2 1
6
1 1 2 2 3 4

Output
YES
NO
YES
N


Source Code – Below source code is using JavaScript Language

function isDominantElementPresent(arr) {
   
   var count = {};
   arr.forEach(ele=>{
    if(count[ele]){
        count[ele] +=1;
           
    }else{
        count[ele] = 1;
    }
});

var maxFrequency = 0;
 for (var ele in count) {
            maxFrequency = Math.max(maxFrequency, count[ele]);
    }
    var isDominant = Object.values(count).filter(freq => freq === maxFrequency).length === 1;
    
return isDominant;
}




function main() {
    const t = parseInt(prompt("Enter the number of test cases:"));

    for (let i = 0; i < t; i++) {
        const n = parseInt(prompt("Enter the size of the array:"));
        const arr = prompt("Enter the array elements separated by space:")
            .split(" ");

        if (isDominantElementPresent(arr)) {
            console.log("YES");
        } else {
            console.log("NO");
        }
    }
}

main();

Flutter FVM – Multiple SDK versions Management

0
Flutter Version Management - fvm
Flutter Version Management - fvm

Hi Guy’s Welcome to Proto Coders Point. In this Article let’s learn about FVM and how to use multiple flutter sdk on same system/PC/laptop.

What is FVM?

FVM stands for Flutter Version Management a tools that allows you to work with multiple flutter SDK versions on the particular flutter project. Useful when there is frequent switch between flutter channels, When you use normal flutter sdk channel switches are slow and need time to repeatedly reinstall and set sdk globally but by using FVM it’s easy to install and switch between channels & flutter versions easily and in quick time..

How to install FVM?

Installing FVM in Windows

Open command prompt and run below installation cmd to install fvm globally

dart pub global activate fvm

Installing FVM in MacOS

Run below command to install fvm in macOS

brew tap leoafarias/fvm
brew install fvm

Install FVM in Linux/Ubuntu

brew tap leoafarias/fvm
brew install fvm

Set Environment Variable System Path

Open Environment Variable > System Variable > Path > New, Then copy below path.

C:\Users\Asus\AppData\Local\Pub\Cache\bin

Once done, Close the running terminal, then restart it and run fvm to check if fvm path is successfully set.


Once the fvm installation is completed and environment is set, then we need to install desired version of flutter sdk using FVM cmd. follow below step.

How to install multiple flutter sdk & use it for flutter project

First we need to get all the released version of flutter sdk available to be installed, then apply it on a particular flutter project and use it.

Get list of all released version of flutter sdk

fvm releases

get list of all flutter sdk version using fvm releases cmd

Install Multiple Flutter SDK using fvm

Now, once you have the list of flutter sdk version, you can install any number of flutter sdk version using the version number you desired to install.

To Install fvm flutter sdk version use below cmd:

fvm install <version>

Example let’s say I want to install latest flutter sdk version 3.19.2, then i need to run cmd fvm install 3.19.2.

Get List of all Install fvm flutter sdk that we can used in switching between flutter version and channel

To get list of all flutter sdk installed using fvm run below cmd:

fvm list

fvm list to get list of all flutter sdk installed  using fvm

Config/Apply a desired flutter SDK to a project

now Finally after installing fvm flutter sdk to use it or to apply specific version of flutter sdk toa flutter project you can use below code

fvm use <version>

Example: I have install flutter sdk version 3.10.2 and I want to apply this sdk version to one of my flutter project, then simple in root folder of your flutter project run fvm use 3.10.2.

once fvm use cmd is done, In your flutter project .fvm folder will automatically get created which will have few files defining which version of flutter sdk which it should you use for this flutter project.

FVM – Flutter Multiple SDK versions Management Video Tutorial