Home Blog

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

Array Manipulation and Array Methods in TypeScript

0
Types of Array Methods in typescript
Types of Array Methods in typescript

Hi Guy’s Welcome to Proto Codes Point, In this TypeScript Tutorial let’s check out Array Manipulation & Methods in TypeScript.

What is Array Manipulation?

In TypeScript Array Manipulation is a technique of performing various operations on arrays to add, remove or update elements of Arrays. This Allows you to change the contents within the array dynamically as required.

Benefits of Array Manipulation

  • Allows for dynamic modification of array contents based on changing requirements.
  • Provides flexibility in managing data structures & performing operations efficiently.
  • Enables Implementation of various algorithms & solving real-world problems effectively.

Array Methods in TypeScript

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • concat()
  • slice()
  • indexOf()
  • includes()
  • forEach()
  • join()
  • reverse()
  • filter()
  • map()
  • find()
  • findIndex()
  • every()
  • some()
  • sort()

Method Explanation

push(): Adds one or more elements to the end of an array. Real-life example: Adding items to a shopping cart.

let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
shoppingCart.push("Orange", "Grape");

pop(): Removes the last element from an array. Real-life example: Removing the last item from a stack.

let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
shoppingCart.pop(); //removes last element i.e.Apple.

shift(): Removes the first element from an array. Real-Life example: Taking the first book from a bookshelf.

let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
let firstItem = shoppingCart.shift(); // Watermelon

unshift(): Adds one or more elements to the beginning of an array. Real-life example: Adding a new books in bookshelf at the starting of the list.

let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
shoppingCart.unshift("Grape" , "Orange"); // "Grape", "Orange", "Watermelon" ,"Apple" 

splice(): Adds or removes elements from an array at a specific position. Real-life example: Modifying ingredients in a recipe.

Real-life exalet shoppingCart: string[] = [ "flour" ,"sugar"];
shoppingCart.splice(1, 1, "Butter"); // Remove "sugar" and add "Butter".

concat(): Combines two or more arrays and returns a new array.

let fruitGroup1: string[] = [ "Watermelon" ,"Apple"];
let fruitGroup2: string[] = [ "Grape" ,"Orange"];
let AllFruits: string[] = fruitGroup1.concat(fruitGroup2); // "Grape", "Orange", "Watermelon" ,"Apple" 

slice(): can be used to selecting a range index from and to from the array and return a new array.

let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
let selectedBooks: string[] = fruits.slice(1,3); ["Orange", "Watermelon"] 

Select fruits from index 1 to 2 i.e. [“Orange”, “Watermelon”]


indexOf(): This will return the first index at which the given element is found & in case if element is not found the the array we get -1 as responce.

let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
let firstPosition: number = fruits.indexOf("Orange"); 1
let firstPosition: number = fruits.indexOf("banana"); // -1, because the element is not the the array list

includes(): check if the element exist in the array or no, return boolean value true or false.

let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
let isExist: number = fruits.includes("Orange"); true
let isExist: number = fruits.includes("banana"); false

forEach(): Iterate to each element in the given array.

let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];

fruits.forEach(ele=> console.log(ele));

join(): convert all element into a long string, optionally can add symbols like commas(,) to separate them.

let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];

let joinedFruits: string[] = fruits.join(","); // "Grape, Orange, Watermelon, Apple"

reverse(): Reverses the order of the element in an array.

let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];

fruits.reverse(); //[ "Apple",  "Watermelon" , "Orange", "Grape" ]

filter(): This is used to filter element with a specific condition, if the condition pass the test a new fresh array will be return as per filter login.

// Define an array of numbers
const numbers: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Use the filter method to get even numbers
const evenNumbers: number[] = numbers.filter(num => num % 2 === 0);

console.log("Original array:", numbers); [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log("Even numbers:", evenNumbers); [2, 4, 6, 8, 10] 

map(): The map method in TypeScript is used to iterate each element of an given array & create a new array as per required condition or login. Here’s an example: Below I am just iterating array using map and getting uppercase array in return.

// Define an array of strings
const fruits: string[] = ["apple", "banana", "orange", "grape", "kiwi"];

// Use the map method to create a new array of uppercase fruits
const uppercaseFruits: string[] = fruits.map(fruit => fruit.toUpperCase());

console.log("Uppercase fruits:", uppercaseFruits); ["APPLE", "BANANA", "ORANGE", "GRAPE", "KIWI"]

find(): This is similar to indexOf but not same, Here in find method of TypeScript is used to retrieve the first element in an array that satisfies a given condition. Here’s an example:

// Define an array of objects representing persons
interface Person {
  name: string;
  age: number;
}

const people: Person[] = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 22 },
  { name: "David", age: 35 },
];

// Use the find method to get the first person older than 30
const olderThan30: Person | undefined = people.find(person => person.age > 30);

console.log("People array:", people);
console.log("First person older than 30:", olderThan30);

findIndex(): The findIndex method in TypeScript is similar to find, but instead of returning the element itself, it returns the index of the first element in an array that satisfies a given condition.

// Define an array of objects representing persons
interface Person {
  name: string;
  age: number;
}

const people: Person[] = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 22 },
  { name: "David", age: 35 },
];

// Use the find method to get the first person index value older than 30: 
const olderThan30: Person | undefined = people.find(person => person.age > 30);

console.log("People array:", people);
console.log("First person older than 30 it index is :", olderThan30); // 3 

every(): The every method in TypeScript is used to check if all elements in an array satisfy a given condition. It returns a boolean value. Here’s an example:

// Define an array of numbers
const numbers: number[] = [2, 4, 6, 8, 10];

// Use the every method to check if all numbers are even
const allEven: boolean = numbers.every(num => num % 2 === 0);

console.log("Numbers array:", numbers);
console.log("Are all numbers even?", allEven);

some(): The some method in TypeScript is used to check if at least one element in an array satisfies a given condition. It returns a boolean value. Here’s an example:

// Define an array of numbers
const numbers: number[] = [1, 3, 5, 7, 9, 10];

// Use the some method to check if at least one number is even
const hasEvenNumber: boolean = numbers.some(num => num % 2 === 0);

console.log("Numbers array:", numbers);
console.log("Does the array contain at least one even number?", hasEvenNumber);

sort(): The sort method in TypeScript is used to sort the elements of an array. By default, it sorts the elements as strings, but you can provide a custom comparison function to define the sorting order. Here’s an example:

// Define an array of strings
const fruits: string[] = ["banana", "apple", "orange", "kiwi", "grape"];

// Use the sort method to sort the array alphabetically
const sortedFruitsAlphabetical: string[] = fruits.slice().sort();

console.log("Original array:", fruits);
console.log("Sorted array (alphabetical):", sortedFruitsAlphabetical);

// Use the sort method with a custom comparison function to sort by length
const sortedFruitsByLength: string[] = fruits.slice().sort((a, b) => a.length - b.length);

console.log("Sorted array (by length):", sortedFruitsByLength);

In the first part of the example, the sort method is used without any arguments to sort the fruits array alphabetically. Keep in mind that sort modifies the original array, so it’s a good practice to create a copy using slice() before sorting.

In the second part, a custom comparison function is provided to the sort method, sorting the array based on the length of the strings. The comparison function takes two elements, a and b, and returns a negative value if a should come before b, a positive value if a should come after b, or zero if they are equal.

Conclusion

Array manipulation involves performing operations like adding, removing or modifying elements within the arrays. Understanding array manipulation is very much essential for building applications that involving playing with data or processing the list of datas.

Solution: Unknown flutter tag | How to Upgrade Flutter SDK

0
Unknown flutter tag - flutter upgrade
Unknown flutter tag - flutter upgrade

Hi Guy’s Today when I was trying to upgrade my flutter sdk to latest version i.e. 3.19 I was facing an error/warning been showing “Unknown flutter tag. Abandoning upgrade to avoid destroying local changes. it is recommended to use git directly if not working on an official channel.

To fix this all you need to do is you need to run “flutter upgrade” command in the flutter sdk folder itself from the command prompt and also make sure to run the command prompt as administrator.

Video Tutorial

Alphabets Spinning A – Z & Picking Random Letter with Javascript

0
Alphabet Spin A-Z & Pick Random Letter
Alphabet Spin A-Z & Pick Random Letter

Hey, everyone! In this Tutorial, we’ll explore HTML with Javascript, demonstrating an alphabet spin from A to Z Similar to Instagram’s video effect/filter where an alphabet spins from A to Z on top of the head, we’ll also pick a random letter from A to Z and display it.

In the World of Web Development JavaScript plays an top important role in giving or adding interactive dynamic features like animation to web apps. On fascinating Example is here to Spin the Alphabets from A-Z and generate a random alphabet from it and display it.

Video Tutorial

Source Code

html

<!DOCTYPE html>
<html>
  <head>
    <title>Hello World!</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
      <h1 class="title">Hello World! </h1>
      <div id="alpha">A</div>
      <script src="script.js"></script>
  </body>
</html>

Here In HTML Code I have added a div container with id as “alpha” so that i can control div tag from javascript code.


Javascript

var alphabets = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

var i = 0;
var loopNo = 0;

function update() {
  document.getElementById('alpha').innerHTML = alphabets[i];

  i++;
  if(i == alphabets.length){
    i = 0;
    loopNo++;
  }
  if(loopNo == 1){
    var randomIndex = Math.floor(Math.random() * alphabets.length);
    var randomAlphabets = alphabets[randomIndex];
    console.log(randomIndex);
    clearInterval(intervalId);
    document.getElementById('alpha').innerHTML = randomAlphabets;
  }
}

var intervalId = setInterval(update, 100);

Now, let’s check out the javascript code to interact with HTML. The <div> tag/element by using its id ‘alpha’ where the alphabets will be dynamically displayed rapidly A-Z in a loop wise.

Code Walkthrough:

  1. Alphabets Array: The script initializes a string alphabets containing all uppercase English letters.
  2. Variables Initialization: Two variables, i and loopNo, are initialized to keep track of the current alphabet index and the number of loops.
  3. Update Function: The update() function is responsible for updating the content of an HTML element with the id ‘alpha’ with the current alphabet.
  4. Loop Control: The function increments the index i and resets it to 0 when it reaches the length of the alphabet string, simulating a continuous loop.
  5. Random Alphabet Generation: After the first loop (loopNo == 1), the code selects a random index from the alphabet string and displays the corresponding letter. The setInterval is then cleared, stopping the continuous update.

Conclusion:

In conclusion, This JavaScript code help you in understanding basic of JS like how to make use of setInterval() to call a function repeatedly and perform an event like dynamically changing HTML div tag TextContent and also how to stop the setInterval() using clearInterval(). Such scripts can be used for educational purposes, creating interactive quizzes, or simply for adding a playful touch to a website.