Home Blog

How to store data locally in Flutter – 5 Ways

0
5 Ways to Store Data in Flutter App Offline/Locally
5 Ways to Store Data in Flutter App Offline/Locally

Hi Guys, Welcome to Proto Coders Point. In this article on Flutter Dart let us know all the ways by which we can store data offline locally in Flutter App itself. Let’s get Started.

There are n number of scenarios where the best practice is storing data locally on users devices rather than relying on remote cloud servers or APIs, if we store frequently used data from API call then it can also lead to increase server cost, so it’s better to store as a cache into local database in flutter app . For Example, your flutter app might want to store data between app sessions or download a language dictionary from the internet for offline access.

Flutter SQLite

SQLite is a lightweight, fast, self-contained, and reliable SQL database engine written in C. It is embedded in all mobile devices and is commonly included in many applications used daily.

For beginners, SQLite queries might seem complex, but it simplifies operations like INSERT, READ, UPDATE, and DELETE basicallyt using SQLite we can perform CRUD operation locally in mobile devices.

Key Note:

Flutter SQLite library is very small, I means the The library size (engine that runs SQLite) is 400–500 KB and the data storage capacity depends on the memory size the mobile device is allocated.

Example of Flutter SQLite

In Futter, We have a package/Plugin using which you can work with SQLite DB i.e. sqflite


Hive Database in flutter

Hive Database is built using pure DART language, Hive DB is a lightweight & fast key-value NOSQL Database. Which is similar to MongoDB, HIVE DB can be used as best alternative of SQLite Database.

To make use of HIVE Database in Flutter we must download 2 package Hive & hive_flutter

More Implementation details you can check the article: Link

Hive make use of box in which we can store the data we need by using put or get method

Example:

var box = Hive.box('myBox'); // Create a box
box.put('name', 'Rajat'); // store the data in key-value pair
var name = box.get('name');  //retrive the data using get by passing key
print('Name: $name'); // Rajat

Shared Preferences Storage in flutter

Shared Preferences is the most widely used plugin as a simple storage medium. It make use of NSUserDefaults on iOS and macOS and SharedPreferences on Android. While data can be saved to disk asynchronously, it is not guaranteed that writes will persist immediately.

Shared Preferences is best to use for non-critical data storage, may be to keep user logged into the app, user settings or small key-value pairs.

Syntax Example:

SharedPreferences prefs = await SharedPreferences.getInstance();

// Reading data
String name = prefs.getString('name');
   
// Updating
await prefs.setString('name', 'Some Value');

Read our Tutorial about how to use Shared Preferences in Flutter App

Flutter Sharedpreferences Alternative | GetX Storage | keep user loggedIn
Shared preferences to keep user logged in flutter app


ObjectBox in flutter

ObjectBox is basically a dart-native key-value database, which is some what similar to Hive. It is designed for speed query , enhancing the data response times and ObjectBox also supporting real-time applications. In Flutter Dart ObjectBox Highly compatible with OS like: Android, iOS, macOS, Linux, and Windows, offering built-in support for object links and relationships.

Although it delivers excellent performance, But as ObjectBox is still new in database market it required time to mature and prove its reliability in large-scale projects.

A Quick Example on ObjectBox in Flutter Dart:

@Entity()
class PersonData {
  int id;

  String firstName;
  String lastName;

  PersonData({this.id = 0, required this.firstName, required this.lastName});
}

final store = await openStore(); 
final box = store.box<PersonData>();  // Creation on ObjectBox Box

var personObj = PersonData(firstName: 'John', lastName: 'Doe');

final id = box.put(personObj );  // Create

personObj = box.get(id)!;       // Read or simple get the data stored in Object

personObj .lastName = "Doe Doe Doe";
box.put(personObj );             // Update the lastname

box.remove(personObj .id);  

Realm Database in flutter

Realm is an open-source free to use Database, mobile-first database designed to store offline data persistence in Flutter applications. Developed by the same company behind MongoDB, Realm in Flutter offers a NoSQL key-value structure, making it a powerful tool for mobile app development.

To add Realm to your Flutter project, simply run:

flutter pub add realm

Here is an Example on Realm is object-oriented data model, The Data Structure is Data Model is Defined as below:

import 'package:realm/realm.dart';  
part 'app.g.dart'; 

// define a data model class named _User
@RealmModel() 
  class _User {
    late String emal;

    late String name;

    int? age = 18;
}

Then you need to generate a RealMObject Class, To do that just run execute below command:

flutter pub run realm generate

Then now you can create and save the new user into your RealM Database as below:

var config = Configuration.local([User.schema]);
var realm = Realm(config);

var userOne = User("hello@kindacode.com", "Mr. Hello", age: 100);
  realm.write(() {
    realm.add(userOne);
});

Consultion

In this article we check different way by which we can store data locally/Offline into Mobile device using Mobile Storage.

Solution to “Not a Valid Dart Package Name” Error in Flutter

0
Not a Valid Dart Package Name - Flutter
Not a Valid Dart Package Name - Flutter

Naming conventions play a crucial role when developing applications with Dart and Flutter. One of the common issues developers face is the “not a valid Dart package name” error, which typically occurs due to improper naming of packages or directories. In this article, we’ll explore the root cause of this error, why it happens, and how you can fix it by adhering to Dart’s package naming rules.

Understanding the Error

The error message “not a valid Dart package name” usually pops up when the name of the package or directory doesn’t comply with Dart’s strict naming conventions. Dart has specific rules for how package names should be structured, and violating these rules will result in build failures or errors when trying to run or publish the package.

In Flutter, this error often arises because the name of your project folder is automatically used as the package name in your project configuration files. If your directory name doesn’t follow the appropriate naming conventions, the Dart or Flutter SDK will flag it as invalid.

Flutter SDK and Package Naming Conventions

The reason this error is so prevalent in Flutter is that the SDK uses the directory or folder name as the package name. This means that if your folder name has invalid characters, it will be reflected in your package name, triggering the error. For instance, if you name your directory myBmiCalculator, you’ll likely encounter this error because it contains capital letters, which are not allowed in Dart package names.

To avoid this, Flutter enforces a specific set of rules:

  • Package names must be all lowercase.
  • Underscores (_) should be used to separate words instead of spaces or hyphens.
  • Only basic Latin letters and Arabic digits ([a-z0-9_]) are allowed.
  • The name cannot start with digits, and it should not be a reserved word in Dart.

Common Mistakes in Naming Packages

Developers, especially those new to Flutter and Dart, often make simple mistakes in package naming that lead to errors. Here are some common pitfalls:

  1. Capital letters: Dart package names cannot contain any capital letters. For example, myBmiCalculator is invalid because of the capital “B” and “C”.
  2. Hyphens: While many programming languages allow the use of hyphens in package names, Dart does not. A name like my-bmi-calculator would result in an error.
  3. Starting with a digit: Dart does not allow package names to start with numbers. So, a name like 123calculator would also be invalid.
  4. Spaces: Using spaces in package names is not allowed. A package name like my bmi calculator will result in an error.

Example of an Invalid Package Name

Suppose your project folder is named MyBMICalculator. When Flutter tries to use this as the package name, you’ll encounter an error because the package name:

  • Contains capital letters.
  • Does not use underscores to separate words.

To fix this, you would rename your folder (and the package name) to my_bmi_calculator, which adheres to Dart’s naming rules.

How to Fix the Error

To resolve this error, you simply need to follow Dart’s package naming conventions:

  1. Rename your project folder: Ensure that the folder name only uses lowercase letters, digits, and underscores. For example, rename MyBMICalculator to my_bmi_calculator.
  2. Modify the package name in configuration files: If renaming the folder alone doesn’t fix the issue, ensure that the new name is correctly reflected in your pubspec.yaml file and any other configuration files where the package name appears.

For instance, update the pubspec.yaml file:

name: my_bmi_calculator

Once you’ve made these changes, the error should be resolved.

Best Practices for Naming Dart Packages

  • Use lowercase letters: Keep the package name in all lowercase to avoid errors.
  • Use underscores: Separate words with underscores to improve readability and maintain compliance with Dart’s rules.
  • Avoid special characters: Stick to letters, numbers, and underscores. Hyphens, spaces, and other special characters are not allowed.
  • Keep it descriptive: The name should describe the package or app’s functionality. A descriptive, valid name improves clarity and discoverability.
  • Check for existing names: Before naming your package, check pub.dev to ensure your chosen name isn’t already taken.

Tools to Validate Package Names

You can use tools to validate your package names:

  • pub.dev: The official Dart package repository lets you search for existing package names to avoid duplicates.
  • Dart Analyzer: Integrated into most Dart IDEs, this tool flags any invalid package names during development.
  • pub publish command: Running pub publish in your terminal validates the package name before it’s published to pub.dev.

Conclusion

The “not a valid Dart package name” error is easy to resolve once you understand Dart’s strict naming conventions. By ensuring your package name is lowercase, uses underscores, and avoids hyphens and digits at the beginning, you can fix this error and continue developing your Flutter app without issues. Following best practices for naming packages ensures smooth development, better discoverability, and compatibility with the Dart ecosystem.

Node.js and Express.js Explained: Building Scalable Web Applications

0
nodejs

Introduction on NodeJS

  • Brief description of Node.js
    Node.js is an open-source, cross-platform JavaScript runtime environment by using which web developer can execute JavaScript code server-side. Basically JS is a client i.e browser side langauge and can we only run on browser. Thus NodeJS help backend developer to run javascript on server side. NodeJS make it possible to build scalable and high-performance server-side applications.
  • Importance and Relevance in Modern Web Development
    As we all know that NodeJS Architecture is a non-blocking, event-driven architecture, Now a days Node.js is used widely across world for building fast, scalable, and real-time web applications. Currently NodeJS is used by tech giants like Netflix, LinkedIn, and Uber to power their backend systems.

What is Node.js?

  • Definition and Basic Explanation
    Node.js is a runtime environment that lets you run JavaScript outside of the browser. It uses the Chrome V8 engine to execute JavaScript code, allowing developers to build server-side applications using JavaScript.
  • History and Evolution of Node.js
    Node.js was created by Ryan Dahl in 2009 to address limitations in existing server-side technologies, particularly the inability to handle multiple concurrent connections efficiently. Since then, it has grown into one of the most popular backend technologies.
  • Key Features and Benefits
    Some key features of Node.js include:
    • Event-Driven & Asynchronous: This Feature handle multiple requests simultaneously without getting blocked.
    • Scalability: Node.js multiple connections feature builds scalable applications.
    • Lightweight & Fast: NodeJS V8 engine & non-blocking I/O, can execute code much faster & handle more requests per second.

How Node.js Works

  • NodeJS Event-Driven, Non-Blocking I/O Model
    Node.js make use of an event-driven architecture, That makes the server to process any incoming requests in a asynchronous order. This non-blocking I/O feature of NodeJS enables it to handle any large amount of concurrent requests efficiently, without waiting for other operations like database queries or file reading to complete.
  • Single-Threaded Nature and Its Implications
    U Know? NodeJS or JavaScript make use of only one single thread, To handle multiple request it uses an event loop and callbacks to handle asynchronous operations. This makes it more efficient for I/O-bound operations, though it may not be as effective for CPU-intensive tasks.

Core Components of Node.js

  • Node.js Runtime Environment
    The runtime environment includes the V8 engine and Node.js APIs that allow JavaScript to interact with the system’s hardware and services.
  • npm (Node Package Manager)
    npm is the default package manager for Node.js, offering a vast repository of reusable libraries and tools to streamline development.
  • Built-in Modules and Libraries
    Node.js comes with a set of built-in modules such as HTTP, File System (fs), and Stream, allowing developers to perform various server-side operations without the need for external libraries.

Node.js vs. Traditional Server-Side Technologies

  • Comparison with Other Server-Side Languages (e.g., PHP, Ruby)
    Compared to traditional server-side technologies like PHP and Ruby, Node.js offers faster performance, thanks to its non-blocking architecture. However, it may not be the best choice for CPU-intensive operations, where languages like Python or Java can excel.
  • Advantages and Disadvantages of Using Node.js
    Advantages:
  • High scalability for real-time applications.
  • Large ecosystem of modules via npm.
  • Fast execution and efficient resource utilization.
    Disadvantages:
  • Not ideal for heavy computational tasks.
  • Relatively new, so less mature than traditional technologies.

Introduction to JavaScript in Node.js

  • Role of JavaScript in Node.js
    JavaScript is used as the primary language for developing applications in Node.js, both client-side and server-side, making it possible to use a single language across the entire application stack.
  • Differences Between Client-Side and Server-Side JavaScript
    Client-side JavaScript manipulates the DOM and handles user interactions in the browser, while server-side JavaScript in Node.js handles database operations, HTTP requests, and server logic.
  • Common Use Cases for JavaScript in Node.js Applications
    Node.js is commonly used for real-time applications (e.g., chat apps), RESTful APIs, single-page applications (SPAs), and microservices.

Express.js: The Popular Node.js Framework

  • What is Express.js?
    Express.js is a minimal and flexible Node.js web application framework that simplifies building web servers and APIs.
  • Key Features and Benefits of Using Express.js
    Express.js offers middleware, routing, and templating functionality out of the box, reducing the amount of boilerplate code needed for web applications.
  • How Express.js Simplifies Web Application Development
    Express.js abstracts many of the complexities involved in setting up a Node.js server, providing a cleaner and more organized structure for handling HTTP requests, routing, and middleware integration.

Building a Simple Application with Node.js and Express.js

  • Setting Up a Node.js Environment
    Install Node.js from the official website and verify the installation using the node -v command.
  • Installing and Configuring Express.js
    Install Express.js using npm: npm install express. Create a basic Express server by initializing a new Node.js project with npm init.
  • Creating a Basic Web Server
    Here’s a basic example to set up a web server using Express.js:
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
  • Handling Routes and Middleware
    In Express.js, you can easily handle routes using app.get, app.post, and other HTTP methods. Middleware functions allow you to handle requests and responses.

Real-World Applications of Node.js

  • Examples of Popular Applications Built with Node.js
    Some notable examples include LinkedIn, Netflix, PayPal, and Uber, which all use Node.js to handle millions of concurrent users.
  • Industries and Scenarios Where Node.js Excels
    Node.js excels in building real-time applications like chats, live feeds, and online gaming. It’s also used in microservices architectures and data streaming applications.
  • Case Studies and Success Stories
    For instance, LinkedIn switched from Ruby on Rails to Node.js and saw a significant increase in performance, reducing the number of servers they needed by 10x.

Advantages and Disadvantages of Using Node.js

  • Pros of Using Node.js for Web Development
  • Non-blocking I/O for handling concurrent requests.
  • Lightweight and efficient.
  • Single language (JavaScript) across the stack.
  • Cons and Potential Challenges
  • Not well-suited for CPU-bound operations.
  • Callback-heavy code (though mitigated by async/await).
  • Best Practices for Overcoming Common Issues
  • Use tools like PM2 for process management.
  • Optimize asynchronous code with promises or async/await.

Learning Resources and Community Support

  • Recommended Tutorials and Courses for Learning Node.js
    Popular platforms like Udemy, Coursera, and freeCodeCamp offer comprehensive Node.js tutorials.
  • Online Communities and Forums for Node.js Developers
    Join communities on Stack Overflow, GitHub, and Reddit for support and knowledge sharing.
  • Books and Documentation for In-Depth Understanding
    Books like “Node.js Design Patterns” and the official documentation at nodejs.org are excellent resources for deep learning.

Conclusion

Node.js has revolutionized web development by allowing JavaScript to be used on the server side. With its fast performance, large ecosystem, and ease of scalability, it is a popular choice for modern web applications. Whether you are a beginner or an experienced developer, Node.js offers vast opportunities for building efficient and scalable web apps.

Additional Resources

How to Remove White Spaces from String: Dart (Flutter) Language

0
Remove whitespace dart flutter
Remove whitespace dart flutter

Hi Guy’s Welcome to Proto Coders Point.

If you are unaware of what is consecutive white spaces in a string, then let me tell. This consecutive white spaces are basically a multiple spaces that are in a given sentences for example: “Hi Bro. Welcome to ProtoCodersPoint.com” here you can see that in a sentence of string there are while spaces. But this won’t look good and also occupy blank space.

In this Flutter Dart Article let’s walk through the way by which we can remove consecutive white space and keep only single white space.

1. Using dart regular Expression (i.e. RegExp)

In Below Example we will make use of (RegExp) method in dart, Here we will pass a regular expression by which it will match all the whitespace characters in the string and then replace them with the single space. This can be implemented by using the replaceAll() method of the string class in dart.

Below are the steps to be followed

1. Firstly match one or more while space characters in a string by creating a RegExp object with the pattern r"\s+".

2. Call the replaceAll method on the string and pass the RegExp object and a single space as arguments.

3. Return or print the resulting removed white space from the string.

Code Example below.

// main.dart
import 'package:flutter/foundation.dart' show debugPrint;

// Define a function that removes multiple spaces from a string
String removeMultipleSpaces(String input) {
  // Create a RegExp object with the pattern r"\s+"
  RegExp whitespaceRE = RegExp(r"\s+");

  // Replace all the white space characters with a single space
  String output = input.replaceAll(whitespaceRE, " ");

  // Return the resulting string
  return output;
}

void main() {
  String input = "Hi   buddy. Welcome    to    Proto Coders Point.";
  String output = removeMultipleSpaces(input);
  debugPrint(output);
}

2. Using split() and join()

An another way to remove white space from a string is by making use of split() and join() method of the string class. split() method will split the given input string into a list of substrings based on the white space characters and then use the join() method to join them back into the single string with a single space as the separator.

Example program

// main.dart
import 'package:flutter/foundation.dart' show debugPrint;

// Define a function that removes multiple spaces from a string
String removeMultipleSpaces(String input) {
  // Split the input string into a list of substrings
  List<String> substrings = input.split(" ");
  // Remove empty substrings from the list
  substrings = substrings.where((substring) => substring.isNotEmpty).toList();

  // Join the substrings back into a single string with a single space as the separator
  String output = substrings.join(" ");

  // Return the resulting string
  return output;
}

void main() {
  String input =
      "ProtoCodersPoint is    a  website to get solution   to Programming methods.";
  String output = removeMultipleSpaces(input);
  debugPrint(output);
}

3. Using StringBuffer and for loop

Here is an another way to remove white spaces from a given string, and that is by making use of Dart StringBuffer() object and then loop it using simple for loop, While Looping each character from the string will check if the character if white space, if not then append the character to the StringBuffer() object and then after the loop is completed finally step is to convert the buffer object to a string by using .toString() method.

Example program:

// main.dart
import 'package:flutter/foundation.dart' show debugPrint;

// Define a function that removes multiple spaces from a string
String removeMultipleSpaces(String input) {

  // Create a StringBuffer object with an empty initial content
  StringBuffer buffer = StringBuffer();

  // Create a boolean variable to keep track of whether the previous character was a white space character or not
  bool prevIsSpace = false;

  // Use a for loop to iterate over each character in the input string
  for (int i = 0; i < input.length; i++) {
    // Get the current character
    String char = input[i];

    // If the current character is not a white space character
    if (char != " ") {
      // Append it to the buffer and set the boolean variable to false
      buffer.write(char);
      prevIsSpace = false;
    }
    // If the current character is a white space character and the boolean variable is false
    else if (!prevIsSpace) {
      // Append it to the buffer and set the boolean variable to true
      buffer.write(char);
      prevIsSpace = true;
    }
    // If the current character is a white space character and the boolean variable is true, do nothing
  }

  // Convert the buffer into a string
  String output = buffer.toString();

  // Return the resulting string
  return output;
}

void main() {
  String input =
      "ProtoCodersPoint is    a  website to get solution   to Programming methods.
";
  String output = removeMultipleSpaces(input);
  debugPrint(output);
}

Conclusion

In this Article, We learnt how to remove consecutive white spaces from a given sentence(string) by 3 different way as stated above.

JavaScript Beginner to Advanced Day 1 to 12

0
JavaScript Begineer to Advance
JavaScript Begineer to Advance

In current generation JavaScript is backbone of web development, enabling dynamic, interactive websites & applications, Now JS is also been used as server side backend programming language used as to build server. Whether you’re a complete beginner or someone with some coding experience, In this quick guide will take you to topic to study on daily to learn JavaScript from the basics to advanced concepts, making yourself to build a strong foundation in JavaScript concepts. Follow this Article on Day wise like Day 1 basic like wise Each day focuses on a specific topic. By following this article by the end, you’ll have good knowledge on JavaScript and will be able/ready to complete more complex projects.

Day 1: Introduction to JavaScript

Start your journey by knowing about JavaScript & it’s history.

What is JS?

JavaScript is a High-Level Interpreted Programming Language that is been used to add interactivity & dynamic behavior to Applications.

JS Variables: Containers used to store data. var, let & const.

Data Types: We have 2 types of DataTypes in JavaScript, 1. Primitive & 2. Non-Primitive DataType.
Primitive DataTypes are(String, Number, BigInt, Boolean, Undefined, Null, Symbol).
Non Primitive DataTypes are (Objects, Arrays, Functions, Date).

Operators: Operations in JS are Symbols used to perform operations on variables & values.
Operations like (+ Addition, Subtractions, * Multiplications, / Divisions, % Modules, ** Exponentiation (Power), ++ increments, Decrement, == equal, === Strick equal to, != not Equal to, > greater then, < less then and more )

Functions: In JavaScript Functions are block of code that can be defined once & reused when required. In JavaScript we have Functions likes (Named Function, Anonymous Functions, Arrow Function, Function Expressions, IIFE ( Immediately Invoked Functions Expression), Async Functions and more.


Day 2: Control Flow & Conditionals

Conditional Statement: Learn how to make use of conditional statements like if else if and else or switch for executing different code blocks based on different conditions.

Comparison Operations: As stated above we can make use of Comparison operation such as ==,===,!=,!==,<,>,<=,>=.

Logical Operation: make use of logical condition like && (and operator), || (or operator), and ! (NOT operator), that is mostly used in condition statement like if conditions.

Ternary Operation: This are basically single line statement that act as if else condition.
condition ? exprIfTrue : exprIfFalse


Day 3: Loops & Iterations

Study in depth on all the types of iteration like

for: Execute the code block with the specified number of times.

for (initialization; condition; increment/decrement) {
    // Code block to execute
}

while: Execute the code block until the condition is true.

while (condition) {
    // Code block to execute
}


do…while: This loop will definitely execute at least once before the condition is check

do {
    // Code block to execute
} while (condition);


for…in: Specially used to iterate an object properties.

for (let key in object) {
    // Code block to execute
    // key refers to the object's property names
}


for…of: Iterate over the values of an iterable object like arrays or strings

for (let value of iterable) {
    // Code block to execute
    // value refers to the elements of the iterable
}

Day 4: Arrays & Objects

Arrays: Ordered collections of data/values that can we accessed by using numeric indices.

Array method: Learn how to make use of Arrays predefined functions using which we can manipulate array content, such as push(), pop(), shift(), unshift() ,splice(), slice() and more.

Objects: Object are basic collections of data that are stored in a form of key-value pairs. JavaScript have also provided objects method that is used to play with object in JS.

Object.assign(), Object.create(), Object.defineProperty(), Object.defineProperties(), Object.entries(), Object.freeze(), Object.fromEntries() and more.


Day 5: Function & Scopes

Learn about what is scope and types of scopes in Javascript

Local Scope: The Variables that are declared within an function are accessable only within that particular function, if used outside will result into undefined.

function localScopeExample() {
    let localVar = "I'm local";
    console.log(localVar); // Accessible here
}

localScopeExample();
console.log(localVar); // Error: localVar is not defined (undefined outside the function)

Global Scope: This are the variable that are accessible anywhere in a code base.

let globalVar = "I'm global";

function globalScopeExample() {
    console.log(globalVar); // Accessible inside the function
}

globalScopeExample();
console.log(globalVar); // Accessible outside the function too

Function Declarations: This function are defined by using function keyword.

function greet() {
    console.log("Hello!");
}

greet(); // Function call

Function Expressions: This are the functions that are defined as expressions, offen assigned to a variable.

const greet = function() {
    console.log("Hello!");
};

greet(); // Function call

Arrow Functions: A more concise syntax for writing functions, using the arrow (=>) syntax.

const greet = () => {
    console.log("Hello!");
};

greet(); // Function call

Day 6: DOM Manipulations

DOM (Document Object Model): A programming interface for web documents, representing the structure of an HTML document as a tree of objects.

Selecting Elements: Methods like getElementById(), getElementsByClassName(), getElementsByTagName(), querySelector(), and querySelectorAll() to select elements from the DOM.

Modifying Elements: Methods like innerHTML, textContent, setAttribute(), classList etc to modify the content and attributes of elements.

Creating & Removing Elements: Methods like createElement(), appendChild(), removeChild() etc to dynamically create & remove elements from the DOM.


Day 7: Event Handling

Events: Any Action performed by user or happen because of triggers are Events.

Event Handlers: This are functions that are triggered only when specific event occurs, such a user clicked on a button is a event.

Event Listeners: Methods like addEventListener() to connect event handlers to an elements.

Event Object: An object containing all the information about the event, passed to event handler functions as an arguments.

Event Propagation: The order in which event handlers are executed.

Event Delegation: Technique for handling events on multiple elements with a single event handler.


Day 8: Asynchronous Operation

Callbacks: A function that is passed as an argument to other functions are called Callbacks, and the callback is executed later.

function fetchData(callback) {
    setTimeout(() => {
        console.log("Data fetched");
        callback();
    }, 1000);
}

function processData() {
    console.log("Processing data");
}

fetchData(processData);  // Output: Data fetched (after 1 second) then Processing data

Promises: A Promise is an object that simply represent event completion or failure on an asynchronous operations.

const fetchData = new Promise((resolve, reject) => {
    let success = true;
    if (success) {
        resolve("Data fetched");
    } else {
        reject("Error fetching data");
    }
});

fetchData.then(result => console.log(result))
         .catch(error => console.log(error));

async/await: Introduced with JavaScript ES6 version to basically write asynchronous code in a synchronous manner.

function fetchData() {
    return new Promise((resolve) => {
        setTimeout(() => resolve("Data fetched"), 1000);
    });
}

async function processData() {
    const data = await fetchData();
    console.log(data);  // Output: Data fetched
}

processData();

XHR (XML HttpRequest): This is an Object used to interact with servers & make HTTP requests from web browsers.

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onload = function () {
    if (xhr.status === 200) {
        console.log(xhr.responseText);
    }
};
xhr.send();

Fetch API: Modern alternative to XHR from making HTTP request in JavaScript.

fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error("Error:", error));

AJAX (Asynchronous JavaScript and XML): Technique for updating part of web page with reloading the whole page.

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        document.getElementById("content").innerHTML = xhr.responseText;
    }
};
xhr.send();

Day 9: ES6 & Modern JavaScript

ES6 (ECMAScript 2015): This is Major Update of JavaScript Language.

Arrow Functions: A more concise syntax for writting functions.

const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5

Template Literals: String that allows embedded expressions.

const name = "John";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, John!

Destructuring Assignment: Extracting values from array or objects & assign it to a variables.

// Array Destructuring
const [x, y] = [10, 20];
console.log(x, y); // Output: 10 20

// Object Destructuring
const person = { firstName: "Jane", age: 25 };
const { firstName, age } = person;
console.log(firstName, age); // Output: Jane 25

Spread Operator: Expands an iterable (like array) into individual elements.

const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5, 6];
console.log(moreNumbers); // Output: [1, 2, 3, 4, 5, 6]

Classes & inheritance: Prototype Inheritance in JS using class syntax.

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks.

Modules: Encapsulating code into reusable modules using import & export statements.

// In math.js (exporting module)
export const add = (a, b) => a + b;

// In main.js (importing module)
import { add } from './math.js';
console.log(add(2, 3)); // Output: 5

Day 10: Advanced JavaScript Concepts

Closures: A Closure are the functions that remembers variables from it’s outer scope, even though the outer function finished its executions. by using Closure in js we can maintain state across function calls.

function outer() {
    let count = 0;
    return function inner() {
        count++;
        console.log(count);
    };
}
const counter = outer();
counter();  // Output: 1
counter();  // Output: 2

ProtoTypes and Inheritance:

This is an mechanism by which JS object inherit feature from one another.

function Person(name) {
    this.name = name;
}
Person.prototype.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
};
const john = new Person("John");
john.greet();  // Output: Hello, my name is John

Context(this): A reference to the object that owns the currently executions code.

const obj = {
    name: "Alice",
    greet: function() {
        console.log(this.name);
    }
};
obj.greet();  // Output: Alice

Execution Context & hoisting:

Here variable declarations is automatically moved to top of their containing scope

console.log(x);  // Output: undefined (due to hoisting)
var x = 5;

Event Loops:

Although JavaScript is a single threaded it make use of Event Loop to perform non-blocking operations.

console.log("Start");
setTimeout(() => console.log("Delayed"), 1000);
console.log("End");
// Output: Start, End, Delayed (after 1 second)

Day 11 & 12: Function Programming & Advanced JS

Here are brief explanations for each of the topics:

Functional Programming:

Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state or mutable data. It emphasizes the use of pure functions, immutability, and higher-order functions to create predictable and maintainable code.

Pure Functions:

A pure function is a function that, given the same input, always returns the same output and has no side effects (i.e., it doesn’t alter any external state or depend on external variables).

function add(a, b) {
    return a + b;  // Pure function: no side effects
}

Immutability:

Immutability means that once a data structure is created, it cannot be changed. Instead of modifying an object, you create a new one with the desired changes, which helps avoid unintended side effects.

const arr = [1, 2, 3];
const newArr = [...arr, 4];  // Creating a new array instead of modifying the original

Higher-Order Functions:

A higher-order function is a function that takes other functions as arguments or returns a function as its result. These are often used to abstract or compose behaviors.

function greet(name) {
    return function(message) {
        console.log(`${message}, ${name}`);
    };
}
const sayHello = greet("Alice");
sayHello("Hello");  // Output: Hello, Alice

Map, Filter & Reduce:

These are common higher-order functions in JavaScript that operate on arrays. map transforms elements, filter selects elements based on a condition, and reduce aggregates elements into a single value.

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);  // [2, 4, 6, 8]
const evens = numbers.filter(n => n % 2 === 0);  // [2, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0);  // 10

Recursion:

Recursion is a technique where a function calls itself to solve a smaller instance of the same problem, often used to solve problems that can be broken down into simpler, repetitive tasks.

function factorial(n) {
    if (n === 1) return 1;
    return n * factorial(n - 1);
}
console.log(factorial(5));  // Output: 120

Module Patterns:

The module pattern in JavaScript is used to encapsulate and organize code, often providing private and public access to methods and variables. This helps avoid polluting the global namespace and creates self-contained units of functionality.

const Module = (function() {
    const privateVar = "I am private";

    function privateMethod() {
        console.log(privateVar);
    }

    return {
        publicMethod: function() {
            privateMethod();
        }
    };
})();
Module.publicMethod();  // Output: I am private

Singleton Pattern:

The singleton pattern ensures that a class or object has only one instance throughout the application, providing a global point of access to it.

const Singleton = (function() {
    let instance;

    function createInstance() {
        return { name: "SingletonInstance" };
    }

    return {
        getInstance: function() {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2);  // Output: true

Observer Pattern:

The observer pattern is a design pattern in which an object (subject) maintains a list of dependents (observers) and notifies them of state changes, allowing for a publish-subscribe mechanism.

function Subject() {
    this.observers = [];
}
Subject.prototype = {
    subscribe: function(fn) {
        this.observers.push(fn);
    },
    unsubscribe: function(fn) {
        this.observers = this.observers.filter(subscriber => subscriber !== fn);
    },
    notify: function(data) {
        this.observers.forEach(observer => observer(data));
    }
};
const subject = new Subject();
const observer1 = data => console.log("Observer 1: " + data);
subject.subscribe(observer1);
subject.notify("Hello");  // Output: Observer 1: Hello

Memoization:

Memoization is an optimization technique that caches the results of expensive function calls and returns the cached result when the same inputs occur again, reducing redundant computations.

function memoize(fn) {
    const cache = {};
    return function(...args) {
        const key = JSON.stringify(args);
        if (cache[key]) {
            return cache[key];
        }
        const result = fn(...args);
        cache[key] = result;
        return result;
    };
}
const factorial = memoize(function(n) {
    if (n === 1) return 1;
    return n * factorial(n - 1);
});
console.log(factorial(5));  // Output: 120 (calculated)
console.log(factorial(5));  // Output: 120 (cached)

These explanations and code snippets provide a quick overview of each concept and how they are used in JavaScript.

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.