Home Blog

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.

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.