Home Blog Page 6

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.

Tips to Boosting Flutter App Performance

0
Tips to Boosting Flutter App Performance
Tips to Boosting Flutter App Performance

Hi Guy’s Welcome to Proto Coders Point. To making your flutter app smooth and better in performance you need to follow some keys points using which you can enhance the performance of your flutter apps.

1. State Management

Making use of State Management in flutter is essential for creating a smooth responsive flutter application.

Ya, Flutter provides it’s default state management ie. setState(). but it has a disadvantage that is it reload full app widget tree just to update few things.

Flutter Developer has to make use of better and optimized State Management Solution to make flutter app perform better.

I recommend to make use of Provider package which offers streamlined state management in flutter.

Example:

To-Do Note App using Flutter Provider


2. Widget Tree Optimization using const

Make use of const constructor on widget where data is not getting updated due to user action.

The const widget make sure that the widget tree & it’s sub child tree will not rebuilt, and prevent unnecessary reload of widget.

By using const keyword in flutter, The widget is instantiated only once during the first build itself.

This will reduce unnecessary load widget or reconstruction and rendering of widget.

class MyTextWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: const Text(
          'Hello, World!',
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}

3. Using Lazy loading & Pagination

Lazy loading & pagination in flutter improve app performance as it reducing memory usage & can speed up the rendering process.

Example:

ListView.builder widget is particularly useful for implementing lazy loading & pagination in flutter app as it has properties like how much data should be loaded i.e. The itemCount parameter using which we can specify total number of items should be shown in the listview.

Code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ListView.builder Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('ListView.builder Example'),
        ),
        body: ListView.builder(
          itemCount: 20, // Number of items in the list
          itemBuilder: (BuildContext context, int index) {
            // itemBuilder builds each item in the list
            return ListTile(
              title: Text('Item $index'),
              subtitle: Text('Subtitle $index'),
              leading: CircleAvatar(
                child: Text('$index'),
              ),
              onTap: () {
                // Action when an item is tapped
                print('Tapped on Item $index');
              },
            );
          },
        ),
      ),
    );
  }
}

4. Image Compressing & resizing

If you have flutter app where you display images to the user’s then implementing image compression will rapidly improve performance of the app.

The flutter_image_compress library provides a convenient solution for achieving this task.

var result = await FlutterImageCompress.compressAndGetFile(
      _imageFile!.path,
      _imageFile!.path, // Destination path (overwrite the original image)
      quality: 50, // Image quality (0 - 100)
    );

Complete Code Example

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Image Compression Example',
      home: ImageCompressionScreen(),
    );
  }
}

class ImageCompressionScreen extends StatefulWidget {
  @override
  _ImageCompressionScreenState createState() => _ImageCompressionScreenState();
}

class _ImageCompressionScreenState extends State<ImageCompressionScreen> {
  File? _imageFile;
  late File _compressedImageFile;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Compression Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _imageFile != null
                ? Image.file(
                    _imageFile!,
                    height: 200,
                  )
                : Text('No Image Selected'),
            ElevatedButton(
              onPressed: () {
                _pickImage();
              },
              child: Text('Select Image'),
            ),
            ElevatedButton(
              onPressed: () {
                if (_imageFile != null) {
                  _compressImage();
                } else {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('Please select an image first.'),
                    ),
                  );
                }
              },
              child: Text('Compress Image'),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _pickImage() async {
    // Code to pick an image from the device's gallery
    // (You can use any method you prefer to pick an image)
    // For example:
    // var imagePicker = ImagePicker();
    // var pickedFile = await imagePicker.getImage(source: ImageSource.gallery);
    // setState(() {
    //   _imageFile = File(pickedFile.path);
    // });

    // For this example, I'm just using a placeholder file path
    setState(() {
      _imageFile = File('/path/to/your/image.jpg');
    });
  }

  Future<void> _compressImage() async {
    // Compress the image
    var result = await FlutterImageCompress.compressAndGetFile(
      _imageFile!.path,
      _imageFile!.path, // Destination path (overwrite the original image)
      quality: 50, // Image quality (0 - 100)
    );

    // Update the UI with the compressed image
    setState(() {
      _compressedImageFile = result!;
    });

    // Show a message indicating success
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('Image compressed successfully.'),
      ),
    );
  }
}

5. Using flutter devTools for performance profiling

To leverage flutter DevTools more effectively, always run your flutter app in profile mode.

How to run flutter app in profile mode, use below command:

flutter run --profile

By running your flutter app in profile mode it gives power to flutter developer that allows app developer to collect detailed app performance data during runTime, Using this data, developer can identify performance bottlenecks, understand resource usage & help developer to optimize their apps accordingly.

6. Implementing network caching in flutter

Utilizing caching header will improve performance & reduce unnecessary network traffic. let’s take an example of of using http package to handle network request like fetching data.

In the provided code snippet, the 'fetchData' function demonstrates the usage of the ‘http’ package to perform a GET request to a specified API. The request includes a ‘Cache-Control’ header with a directive of ‘max-age=3600’, indicating a caching duration of 3600 seconds (1 hour).

Future<void> _fetchData() async {
    final url = 'https://api.example.com/data';
    final response = await http.get(
      Uri.parse(url),
      headers: {'Cache-Control': 'max-age=3600'}, // Caching directive
    );

    if (response.statusCode == 200) {
      // If the server returns a successful response, parse the JSON
      final responseData = json.decode(response.body);
      setState(() {
        _data = responseData['data'];
      });
    } else {
      // If the server did not return a successful response, throw an error
      throw Exception('Failed to load data');
    }
  }
}

Conclusion

Well done on mastering crucial performance optimization techniques. Your apps are now turbocharged, boasting enhanced speed, seamless interactions, and heightened efficiency!

Development with GitHub Copilot – Code Automation AI tool

0
install github copilot in android studio

Hi Guy’s Welcome to Proto Coders Point. In this Article let’s discover how to automate code using GitHub Copilot AI tool.

Below Integrating copilot with IDE for development, Let’s understand:

What is Github Copilot?

  • GitHub Copilat is an AI took developed by GitHub partnering with OpenAI.
  • It assists developers by providing code autocompletion within popular code editor tools or Integrated Development Envirnoments (IDE’s) such as Android Studio, Visual Studio Code, JetBrains, Neovim.
  • This tool is trained on an extensive dataset comparising billions of lines of code that are public and are commonly used by developer.
  • GitHub Copilot uses machine learning & natural language processing to understand context and generate relevant code suggestions.
  • It helps developers save time and stay focused by offering intelligent code completion based on current context effectively.

How to Install Github Copilot?

It’s not hard to install Github Copilot in IDE’s. In this article installing Githuib Copilot into Android Studio IDE.

Follow Below Steps:

In Android Studio IDE just go to Plugin section and search for Github Copilot and click on Install button.

In Android Studio > File > Settings > Plugins

install github copilot in android studio

After Installing it, restart your IDE.

Once you restart your Android Studio IDE you will see “Welcome to GitHub Copilot”.

Just Login with your Github account to use this.

Now your IDE has power to suggest code for you on any language or framework you are working on.

github copilot suggesting code for you

Conclusion

Automated Development AI tools like Githib Copilot helps developer to boost their development speed. Explore the possibilities.

Dart Programs to Calculate mean variance and standard deviation

0
Dart program to calculate mean variance and standard deviation
Dart program to calculate mean variance and standard deviation

Hi Guy’s Welcome to Proto Coders Point. In this flutter dart programming article let’s understand what is mean variance & standard deviation & how to calculate them in dart programming language.

In data analysis, It’s is very crucial to understand the data tendency. mean, variance & standard deviation are main statistical data measures.

What is Mean, Variance & Standard deviation?

Mean:

Mean is calculated by dividing sum of all the numbers in a given set (array)by the total number of numbers. 

Mean = (Sum of all the observations/Total number of observations)


Variance:

Variance is calculated using mean of the squared differences from the average of the data set (array). It is a statistical measure that quantifies the amount of variability or dispersion within a dataset

variance = s^2 = Σ(xi - x̅)^2 / (N - 1);

xi = each value from the data set.
= Mean.
N = Number of value in the data set.


Standard Deviation:

is calculated by square root of variance.

SD = sqrt(variance)


Dart Program to find mean variance and standard deviation

Let’s calculate mean, variance & standard deviation using versatile programming language DART.

import 'dart:math';

void main() {
  List<double> data = [0.6, 1.2, 6, 3, 8, 11, 13, 8, 9.3, 9.4];

  // Calculate the mean
  double mean = data.reduce((a, b) => a + b) / data.length;

  // Calculate the variance
  double variance = data.map((x) => pow(x - mean, 2)).reduce((a, b) => a + b) /
      (data.length - 1);

  // Calculate the standard deviation
  double standardDeviation = sqrt(variance);

  print('Mean: $mean');
  print('Variance: $variance');
  print('Standard Deviation: $standardDeviation');
}

Mean: 6.95
Variance: 17.402777777777782
Standard Deviation: 4.171663670261276


Retrieve a list of dates between two given dates in Flutter Dart

0
Return List of Date between two Dates

There might be a need during the dart/flutter app development where you need to write a function that return list of all the dates between two given list. This functionality is useful in such scenarios where you need to work on date range and display it to the user or on calender into your flutter application.

In this article let’s check out 2 ways by which we can get list of dates between given dates

1. Using DateTime() and Simply use For loop to filter data

List<DateTime> getDaysInBetween(DateTime startDate, DateTime endDate) {
  List<DateTime> days = [];
  for (int i = 0; i <= endDate.difference(startDate).inDays; i++) {
    days.add(startDate.add(Duration(days: i)));
  }
  return days;
}

// try it out
void main() {
 DateTime startDate = DateTime(2024, 2, 1);
  DateTime endDate = DateTime(2024, 2, 10);

  List<DateTime> days = getDaysInBetween(startDate, endDate);

  // print the result without time
  days.forEach((day) {
    print(day.toString().split(' ')[0]);
  });
}

In above example, We have created a function ‘getDaysInBetween’ that accepts 2 parameter i.e. startDate & endDate. This main task of this function is getting all the date between the given date range.

This function will have a for loop that will iterate to endDate using difference method to calculate the number of days between the startDate & endDate.

Then this loop will add each date to the List of type DateTime by incrementing day by 1 using Duration.

Then finally pass two dates to the getDaysInBetween and get the list.

but the date list you receive will also contain time in it so we need to split the time, therefore we make use of forEach loop to iterate the list and print it on screen.

Output


2. Using List.generate() method

List<DateTime> getDaysInBetween(DateTime startDate, DateTime endDate) {
  final daysToGenerate = endDate.difference(startDate).inDays + 1;
  return List.generate(daysToGenerate, (i) => startDate.add(Duration(days: i)));
}

// try it out
void main() {
 DateTime startDate = DateTime(2024, 2, 1);
  DateTime endDate = DateTime(2024, 2, 10);

  List<DateTime> days = getDaysInBetween(startDate, endDate);

  // print the result without time
  days.forEach((day) {
    print(day.toString().split(' ')[0]);
  });
}

You can also get list of dates between any two given dates using simply using inbuilt method of dart language i.e. List.generate().


Speech to Text In Flutter – Speech Recognition

0
Speech to Text in Flutter
Speech to Text in Flutter

Hi Guy’s Welcome to Proto Coders Point, In this Flutter Tutorial will learn how to empower your flutter application with Speech Recognition feature using which user can convert his speak in to text in your flutter application.

Video Tutorial

Speech to Text in Flutter

Giving a feature like Speech to Text in flutter gives a ability to users to easily interact with application by just their voice.

To achieve this we are going to making use of a flutter package called speech_to_text .

Steps to Implement Speech to Text in Flutter App

1. Create A Flutter Project

In your favorite IDE Start by creating a new Flutter Project by using below command if you are using VSCode

flutter create project_name 

Skip this step if you want to integrated Speech to text in existing project, Simple Open the Flutter project where to want to add this feature.


2. Add following flutter depencencies in pubspec.yaml file

Open pubspec.yaml and under depencencies: section add the following line

dependencies:
  speech_to_text:

Then hit below command in terminal

flutter pub get

This will download the speech_to_text package into your flutter project as external library.

To use it simple import it where required example in your flutter project main.dart file.


3. Adding Necessary permission

Android:

In Android module of flutter project open AndroidManifest.xml file and add below permission

Flutter Project > android > app > src > main > AndroidManifest.xml

<uses-permission android:name="android.permission.RECORD_AUDIO"/>

Then to make this package work, We need to have minSdkVersion: 24 and targetSdkVersion: 32. To update it goto build.gradle file

Flutter Project > android > app > build.gradle

iOS:

Same in iOS also we need to permission to access iPhone or iPad device microphone.

Open Podfile, and look for flutter_additional_ios_build_settings(target) and below code in it.

target.build_configurations.each do |config|
     config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] || = [
     '$(inherited)',
     # dart: PermissionGroup.microphone
     `PERMISSION_MICROPHONE=1`,
]
end

Then open Info.plist and inside <dict> </dict> block, add below lines

Flutter Project > ios > Runner > Info.plist

<key> NSMicrophoneUsageDescription </key>
<string> microphone </string>

Flutter initState ask user mic permission

Now we need to add user permission to grant access to use Microphone immediately as our flutter app launch.

SpeechToText speechToText = SpeechToText();

The initState() method is overridden to call CheckMic() method and initialize the microphone availabilty.

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkMic();

  }
void checkMic() async{
    bool micAvailable = await speechToText.initialize();

    if(micAvailable){
      print("MicroPhone Available");
    }else{
      print("User Denied the use of speech micro");
    }
  }

Flutter Speech listener

SpeechToText speechToText = SpeechToText();

speechToText.listen(
        listenFor: Duration(seconds: 20),
        onResult: (result){
        setState(() {
                   textSpeech = result.recognizedWords;
                    isListening = false;
             });
         }
  );

The above code makes use of listen() method that comes in speech_to_text package and start the recording.

Here we have 2 properties listenFor: Specifies the duration the mic to listen to the speech, then the recording speech is stored in onResult result parameter which we can used as result.recognizedWords to convert the speech to text in flutter.

Complete Source – Flutter Speech to Text

main.dart

import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.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 MyHomePage(),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {

  var textSpeech = "CLICK ON MIC TO RECORD";
  SpeechToText speechToText = SpeechToText();
  var isListening = false;

  void checkMic() async{
    bool micAvailable = await speechToText.initialize();

    if(micAvailable){
      print("MicroPhone Available");
    }else{
      print("User Denied th use of speech micro");
    }
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkMic();

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            children: [
                Text(textSpeech),

                GestureDetector(
                  onTap: () async{
                    if(!isListening){
                      bool micAvailable = await speechToText.initialize();

                      if(micAvailable){
                        setState(() {
                          isListening = true;
                        });

                        speechToText.listen(
                          listenFor: Duration(seconds: 20),
                          onResult: (result){
                            setState(() {
                              textSpeech = result.recognizedWords;
                               isListening = false;
                            });
                          }
                        );


                      }
                    }else{
                        setState(() {
                          isListening = false;

                          speechToText.stop();
                        });
                    }
                  },
                  child: CircleAvatar(
                    child: isListening ? Icon(Icons.record_voice_over): Icon(Icons.mic),
                  ),
                )
            ],
          ),
        ),
      ),
    );
  }
}

Similar Tutorials

Text Recognition Using Firebase ML Kit – Text Recognition in Android