Home Blog Page 2

Socket.IO WebSockets Client in Flutter

0
Websocket in flutter socket.io client

What is Socket.IO

Socket.IO in Flutter is a Library using which we can enables or give super power to flutter app by enabling real-time communication between clients and servers. WebSocket Technology is perfect for building Application like realTime chat Application, Online Gaming & More.


How Socket.IO Works

We establish a bidirectional a real-time data transmission between client app (flutter) and backend server which will act a WebSockets Server.

In this article, The Flutter Application will act as the client.

Steps:

  • Establish a connection between Client & the Server.
  • The Flutter App will be listening to any incoming event/message from the server.
  • Emet Evenets to broadcast data to backend.
  • Always Close the connection if no longer needed between client and Server.

In this Flutter Articles, We will learn how to make use of Socket.IO Client into our Flutter Application.

Socket.IO in Flutter

Add Dependencies

Get Started by adding the required dependencies i.e. socket_io_client: package into your flutter project pubspec.yaml file.

dependencies:
  socket_io_client: ^2.0.3+1

Import the Library

Once dependencies is been added successfully, To us it you need to import it where required

import 'package:socket_io_client/socket_io_client.dart' as IO;

Initialize SocketIO in Flutter

IO.Socket socket = IO.io('http://localhost:3000',
  OptionBuilder()
      .setTransports(['websocket']) // for Flutter or Dart VM
      .setExtraHeaders({'foo': 'bar'}) // optional
      .build());


socket.connect();

socket.onConnect((_) => print(" Connected to Server "));

socket.onConnectError(() => print('Connection Error: $err'));

socket.onError((err)=> print("Error"));

socket.onDisconnect((_)=> print('Disconnected from Server"));

Brief Descriptions of each Socket.IO state methods

onConnect: When WebSocket get connected a callback is triggered.

onDisconnect: We can make use of onDisconnect method to keep checking if socket get disconnected due to some socket.

onConnectError:

is been used to handle if an error occur while connection to socket, a callback will be triggered

onError:

In case if any error occurs during message exchanging between client and server, This can be used to handle the error.


Listening to WebSocket Events

To listen to any incoming message of a specific event topic we make use of on method. On Method can be used in flutter app to listen to incoming messages like displaying new chat message in app that too realtime.

void listenToSocketEvent(){

socket.on('eventName' (data){
   print(' Message received: $data');
});

}

Here replace ‘eventName’ with the event name sent from the server.

Emitting or Sending Events to Listeners

When we want to send a message or data to server or broadcast an event to all the listener we make use of emit method. Making use of emit we can transmit messages or data from client to server immediately.

void sendData(){

  final messageData = {

   'messageId':'abcd123',
   'text':'Hello, This is First Message', 
   'sender':'userName',
   'isImportant':true,
   'timestamp':DataTime.now().toIso8601String(),
  }

}

Closing WebSockets

Always remember to close the Socket connection if not needed. Mostly this can be done when used exit the app.

void closeAllSocketConnection(){

   socket.disconnect();
   socket.dispose();

}

Conclusion

In this Flutter Article We integrated the basic setup of Socket.IO Client in our Flutter Application. If you face any error or need personal guide/help feel free to contact me through email: rajatrrpalankar@gmail.com or social network @rajatpalankar.

Try these 7 Free to use APIs

0
free api for developers
free api for developers

In today’s digital world, API’s (Application Programming Interfaces) are very mush helpful for developers out their, That Enables them to add new functionalities & a data sources into the application developer is building. Most of the time Free-to-use API’s provides fresher developer to practice their skill and build a project using the Free API’s. Here in this articles let’s explore 7 Free to use API that can be used in various project whether you are building websites. Mobile Apps or other Applications.

7 Free-to-Use APIs for Developers

1. Coinbase API

This API Service can be used to easily integrate bitcoin, bitcoin cash, litecoin & ethereum real-time cryptocurrency in your application.

coinbase api from crypto currency data

CoinBase API

2. Hotels

This API Helps to Query rooms, price & other info from many hotels around the world, This API can be used by developers who are working on building traveling apps.

api for hotels app building

Hotel API

3. Data USA

Allows developer to explore the entire database to get public US data (Eg: Population Data).

Data USA API

Data USA API

4. IPinfo

This app is useful when you are working on IP address, This gets you information about specific IP address, such as geological info, company name & carrier name etc.

IPinfo api

IPInfo API

5. Weather

Using this API makes it easy to access accurate weather forecasts & get historical weather data.

Weather bit API

6. Google Translate

Allows you to dynamically & easily translate an arbitrary string into any supported langauge.

Google Translate API

7. Alpha Vantage

Alpha Vantage is a simple & effective API using which we can access financial data like stock, ETF, forex, Technical indicators & cryptocurrency data. This API offer real-time and also previous data. Alpha Vantage is the valuable free to use api for developer who are building application related to finance.

Alpha Vantage API

How to Generate Random Nouns in JavaScript

0
How to Generate Random Nouns in JavaScript
How to Generate Random Nouns in JavaScript

Introduction to Generating Random Nouns

In JavaScript knowing how to generate random nouns is very important across a multiple applications, For Example let’s take game development, random noun generation can be used to generate unique and dynamic in-game content, i.e. character names, item lists, or may be even story elements.

The process of generating random nouns in JavaScript involves several key steps:

  • First, create list of nouns from which to generate random nouns will be picked It can be array of noun words or if you want nouns to be picked from any external source like database or API.
  • Second, We will be using JavaScript Built-In Method to randomly pick a number then pick a randon number from the array list index.
  • Finally, The selected noun can be used to show in frontend application.

Building the Random Noun Generator

Below is source code to randomly pick noun basically Noun Generator on js.

Below is an array that contain list of nouns:

const nouns = ["apple", "banana", "car", "dog", "elephant", "flower", "guitar", "house", "ice", "jacket"];

With our array of nouns in place Perfectly, Next is we need to write a javascript function that randomly generate a number that is between the array list length by using JavaScript provides a built-in method, i.e. Math.random(), Then Finally return the noun from the array list using random index number . Here’s a simple function that accomplishes this:

function getRandomNoun() {
  const randomIndex = Math.floor(Math.random() * nouns.length);
  return nouns[randomIndex];
}

In the function getRandomNoun(), we make use Math.random() method to generate a random number between 0 and 1 it will be in decimal 0.01 to 1.0 and then Multiplying this number by the length of the array. Then to make roundup of the number we can use Math.floor() it will round the number to nearest whole number, ensuring it is a valid index. Finally, we return the noun located at this index in the array.

Now simply call the function whenever you need a random noun:

console.log(getRandomNoun()); // Output might be "dog"

In above code in implemented list of Nouns in code itself. That means if we want to add more nouns in the list we need to manually make update to the code. There to enhance the generation on Noun it’s better to dynamically get/fetch the array list from external source like API or Database then pick random noun from the dynamic array list. Below is basic snippet code for reference.

fetch('https://api.datamuse.com/words?rel_jja=noun')
  .then(response => response.json())
  .then(data => {
    nouns = data.map(item => item.word);
    console.log(getRandomNoun());
  });

Dart String Interpolation with Code Example

0
dart string interpolation
dart string interpolation

Hi Guy’s Welcome to Proto Coders Point.

Understanding String Interpolation in Dart

In Dart Variable values can be embedded into string literals. This using Dart String Interpolation we can eliminate technique like we used to do i.e cumbersome string concatenation(Where we use + Operator to concate string), Here with String Interpolation feature in dart provide a clearer way to display String in dart.

By using String Interpolation in dart we can embed variable value or expression inside a string. Syntax looks like this ${expression} or $variableName.

Dart String Interpolation Example 1

Below are few Example by which you get better understanding about String Interpolations

void main() {
  String name = 'Alice';
  int age = 30;

  String greeting = 'Hello, $name! You are $age years old.';
  print(greeting); // Output: Hello, Alice! You are 30 years old.
}

Here in above source code, You can see name & age are two variable with values in it, are embedded into s string greeting by using $name & $age Syntax.

Example 2 – Embedding Expressing Dart String Interpolation

While performing any calculation or while using expression, You need to make use of ${} i.e. curly braces.

void main() {
  int a = 5;
  int b = 3;

  String result = 'The sum of $a and $b is ${a + b}.';
  print(result); // Output: The sum of 5 and 3 is 8.
}

Here a + b is performed and the final string result is embedded into the string.

Example 3 – Multi-Line Strings

void main() {
  String firstName = 'John';
  String lastName = 'Doe';

  String introduction = '''
  My name is $firstName $lastName.
  I am learning Dart.
  ''';

  print(introduction);
  // Output:
  // My name is John Doe.
  // I am learning Dart.
}

In dart by using triple quotes, we can create a multiline string & interpolate the variable into them.

Example 4 – Method & Properties access into String

In dart by using string interpolation syntax we can also include method & property access Example below.

void main() {
  DateTime currentDate= DateTime.now();

  String currentTime = 'Current time is: ${currentDate.hour}:${currentDate.minute}:${currentDate.second}';
  print(currentTime);
  // Output: Current time is: HH:MM:SS (actual time values)
}

Here we are getting current DataTime by using DateTime.now() Class Object, It has several properties like hours, minutes & seconds that we can easily access into strings by using syntax ${currentDate.hours} , ${currentDate.minute} ${currentDate.second}.

Conclusion

String Interpolation in dart is the best way to access values to dynamic strings. By doing this your codes is much more readable & maintainable. Whether you are working with simple string concatenation or complex data representation String Interpolation technique is very must essential in Flutter Dart Programming.

Naming Conventions in Flutter:Best Practices for Clean & Maintainable Code

0
Flutter Naming Convention
Flutter Naming Convention

Hi Guy’s Welcome to Proto Coders Point. In this Flutter Article let’s learn about Naming Convention in Flutter Application development. As you all know that in the world of software development, Giving a Preper naming conventions plays a crucial role in maintaining a clean, understandable, and easily maintainable code. As Flutter, is Developed by Google’s it is a UI toolkit for building natively compiled applications that supports on all the platform may be it’s mobile, web, and desktop that too with a single codebase. By maintaining a proper naming conventions while developing Application in Flutter will not only enhance readability but also make it easier for developers to collaborate on projects. This article will take you to the best practice that you need to follow while using naming convention in flutter.

1. Files and Directories

Files:

  • Use lowercase_with_underscores for naming file names. This kind of format is way easier to read and avoids potential issues with case sensitivity across different operating systems.
  • Example: main.dart, home_screen.dart, user_profile.dart

Directories:

  • Similarly, while creating directories always use this naming convension “lowercase_with_underscores”
  • Example: assets, models, services, widgets

2. Classes

Then comes Classes in dart language. While creating classes names should be written in Pascal Case, where first letter of word starts with an uppercase letter and there sholuld be no spaces or underscores. This kind of naming convention format is mostly common in many programming languages like Java, JavaScript, Python.

  • Example: HomePage, UserProfile, ApiService

3. Methods and Functions

In Dart Methods and functions should be written in camelCase, Means here Method/ Function will start with first letter as lowercase, and can be give uppercase letter for subsequent word.

  • Example: fetchData(), getUserProfile(), handleButtonClick()

4. Variables

Instance variables and local variables:

  • For declaring variables in dart we make use of camelCase, starting with a lowercase letter and capitalizing subsequent words.
  • Example: userName, profilePicture, userAge

Constant variables:

  • For declaring constant variable what will never changed, Make use of Full uppercase letters and can use underscores separating words for better understanding the use case.
  • Example: MAX_USER_AGE, DEFAULT_PROFILE_PICTURE

5. Constants and Enums

Constants:

  • As mentioned above, constants should always be names with all uppercase letters with underscores if needed.
  • Example: const int MAX_RETRIES = 3;

Enums:

  • Enum names should be in PascalCase, and their values should be in camelCase.
  • Example:
    dart enum UserStatus { active, inactive, banned }

6. Widgets

StatelessWidget and StatefulWidget Classes:

  • For State Widget naming convension should be PascalCase convention widget classes.
  • Example: LoginButton, UserCard

State Classes:

  • When defining the state class for a StatefulWidget, This class name should be as Normal at said above and by appending State at the end of class name to make it as widget class name.
  • Example:
class LoginButton extends StatefulWidget { 
@override _LoginButtonState 
createState() => _LoginButtonState(); 
} c
lass _LoginButtonState extends State<LoginButton> 
{
 // State implementation
 }

7. Private Members

Private Memebers in dart are always defined with _ at begin of the naming convension, This can be applied to variable, method or class to make it private member.

  • Example: _fetchData(), _userName, _UserService

8. Mixins

Mixin Variable are maded as PascalCase, At the end of theWord or suffix word Mixin for easily identify the Mixin Variable in dart.

  • Example: LoggingMixin, ValidationMixin

Guide to Docker: Commands, Use Cases, & Benefits

0
docker guide
docker guide

As you all know that Docker is an open-source platform that can be used by any one out their and Docker helps developers to automate their development, scaling, and management of applications through containerization. Basically Docker will encapsulate the applications and all their dependencies into containers, Once application is ready and been containerized Docker ensures that software will runs smoothly in any environments. Below are key benefits of Docker and some very useful commands to get you started as a docker beginner.

Benefits of Docker

Portability: Docker is easily portable on all the machine as it is lightweight and can run consistently across various machines weather it’s local machines to cloud servers.

Scalability: Docker more popular because it is easily scalable, Application wrapped using docker can be easily scaled up or down as per our requirement.

Isolation: Another thing why Docker popular because it can be executed on its own isolated environment, by doing this different applications do not interfere with each other.

Efficiency: Docker containers make use of the host OS kernel i.e it share the host of OS kernel the code, which automatically makes docker more efficient.

Version Control: Version Control is possible in Docker just like how we use Git & GITHUB, This allows developers to keep track all the changes made & roll back to previous versions when necessary.

Use Cases of Docker Commands

Understanding and utilizing Docker commands is very important for managing Docker containers effectively.

Below are few Docker Commands for Beginners level

docker run: Use this command when you need to instantiate a container from an image. It’s essential for testing and development environments.

Example: docker run -it ubuntu


docker ps: Use this command to monitor running containers and check their status. It’s basically useful for managing multiple containers.

Example: docker ps -a lists all containers, whether they are running or stopped, providing a comprehensive overview of container activity.


docker build: Used to create dockerFile of the application. will create a image file of your application in the current working directory and will be names as myapp.

Example: docker build -t myapp .


docker pull: Used to download the Docker File from it Hub, Just like we clone or pull any changed from githu repository. Here docker files will get pulled or downloaded from it HUB.

Example: docker pull postgres


docker exec: used to interact with the running docker container, is been basically used for real-time interacting with docker container that is running. below cmd will open a bash shell with point your running container.

Example: docker exec -it mycontainer bash


By using these commands, Software developers can more efficiently manage their application been wrapped in a Docker containers, streamline application deployment, and maintain robust version control.