Home Blog Page 2

Concurrency in Dart Programming Language

0
Asynchronous programming in Dart
Async/await Dart

As a developer, you might be knowing what concurrency exactly means. Concurrency is the ability to execute more then one task at a given time, means Executing multiple tasks simultaneously, By running multiple task concurrently will enhance the performance & responsiveness of the application. Let’s check out concurrency in dart programming language.

Asynchronous Programming in dart

Basically to perform non-blocking I/O operations & execute task concurrently without affecting or blocking the main thread developer make use of asynchronous programming model that let’s us to run multiple task simultaneously. Async programming in dart will enable responsive & to build scalable dart application.

void main() {
 print("Start");
  
  Future.delayed(Duration(seconds:2),()=>{
    print("Delayed Task 2 second")
  });
  
  print("End");
}

Output

Start
End
Delayed Task 2 second

Here, Start and End print statement will execute immediately and then after 2 second Delayed Task 2 second will get printed.


Future & Async/await

To work with asynchronous operation in dart we have Future function with async/await. Developer can make use of Future object to represent asynchronous computations and async/await syntax to write asynchronous code sequentially.

void main() async {
 print("Start");
  
  await delayedTask(); // waits here for task to complete
  
  print("End");
}

Future<void> delayedTask() async {
  await Future.delayed(Duration(seconds:2),()=>{
    print("Delayed Task 2 second")
  });
}

Isolates in dart

There is another concept been provided by dart i.e. Isolates an lightweight concurrent execution unit that run in seperate memory spaces, with enables a the true parallel processing in dart and isolation of state. Isolate communicate via message passing making them ideal for CPU-bound tasks.

Check out this article on Isolate iin dart – Flutter Isolate – Run Task in Background – MultiThreading for example

Here is simple example on Isolate

import 'dart:isolate';
void main() async {
 ReceivePort receivePort = ReceivePort();
  await Isolate.spawn(isolateFunction, receivePort.sendPort);
  receivePort.listen((data)=>{
    print('Received: ${data}')
  });
}

void isolateFunction(SendPort sendPort){
  sendPort.send("Message fron Isolate");
}

Working with Streams in dart

Stream-based concurrency model is avalilable in dart language that allows developers to process data asynchronously handling streams of data efficiently. Streams in dart facilitate development of event-driven application.

check out this article on streams Flutter Dart Stream Basic Example – Fetch Crypto Currency API Data

Basic Code Example on Streams in dart

import 'dart:async';
void main() async {
 StreamController<int> controller = StreamController<int>();
  
  controller.stream.listen((data){
    print('Received: $data');
  });
  
  controller.add(1);
  controller.add(3);
  controller.add(5);
}

Dart Concurrency model

Dart’s concurrency model revolves around isolates event loops and asynchronous programming primitives. leveraging isolates & async programming, developer can built a super responsive and scalable & high performance application in flutter.

Managing Concurrent Tasks

To manage concurrent task in Dart programming language will involves a proper handling of asynchronous operation, mangaing errors.

Techniques like error handling, cancellation & timeouts are essentials for robust concurrent programming.

Conclusion

Concurrency operation/task in dart programming language are basically used to execute multiple tasks simutaneously using async nature without blocking the main thread.

Integrating Dart with Data Structures and Algorithms (DSA)

0
dsa in dart
Data Structure & Algorithm in dart

Introduction: Building a robust & efficient solutions to real-world programs we can combine Dart Programming language with Data Structures & Algorithms (DSA).

Creating a Dart project for DSA integration

Dart project for integrating with DSA:

  • Install Dart SDK (if not already installed).
  • Create a new Directory for Dart project.
  • open the folder into terminal
  • Now in terminal RUN ‘dart create my_first_dart_dsa_project to create a new dart project into the opened folder/directory.
  • Navigate into the project ‘my_first_dart_dsa_project‘ & start code.

Implementing Data Structure in dart language

You all know that Implementing a good Data Structure will give your dart code a better backbone. Let’s implement essential data structure like lists, Stacks, Queue, Trees etc. that to by using Dart Programming Language.

Below is an example to create Stack in dart:

class Stack<T>{
    List<T> _items = [];
  
    void push(T value){
      _items.add(value);
    }
  
   T pop(){
     if(_items.isEmpty) throw Exception('Stack is Empty');
     return _items.removeLast();
   }
  
  
  bool get isEmpty => _items.isEmpty;

 // Optional: Peek at the top item without removing it
  T get top {
    if (_items.isEmpty) throw Exception('Stack is Empty');
    return _items.last;
  }

}
void main() {
  // Create a stack of integers
  Stack<int> intStack = Stack<int>();

  // Push data onto the stack
  intStack.push(10);
  intStack.push(20);
  intStack.push(30);

  print('Popped: ${intStack.pop()}'); // Should print: Popped: 30
  print('Popped: ${intStack.pop()}'); // Should print: Popped: 20

  // Check if the stack is empty
  print('Is the stack empty: ${intStack.isEmpty}'); // Should print: Is the stack empty? false

  // Push more data onto the stack
  intStack.push(40);
  intStack.push(50);

  // Peek at the top item
  print('Top item: ${intStack.top}'); // Should print: Top item: 50

  // Pop the remaining items
  print('Popped: ${intStack.pop()}'); // Should print: Popped: 50
  print('Popped: ${intStack.pop()}'); // Should print: Popped: 40
  print('Popped: ${intStack.pop()}'); // Should print: Popped: 10

  // Check if the stack is empty again
  print('Is the stack empty? ${intStack.isEmpty}'); // Should print: Is the stack empty? true

  // Attempt to pop from an empty stack (will throw an exception)
  try {
    intStack.pop();
  } catch (e) {
    print('Error: ${e.toString()}'); // Should print: Error: Exception: Stack is Empty
  }
  
}

Output

Popped: 30
Popped: 20
Is the stack empty? false
Top item: 50
Popped: 50
Popped: 40
Popped: 10
Is the stack empty? true
Error: Exception: Stack is Empty

Implementing of Algorithms

Algorithms are specially designed to logically manipulate & process the data efficiently.

Dart Code Example on implement Binary Search algorithm:

// Function to perform binary search on a sorted list
int binarySearch(List<int> list, int searchKey) {
  int low = 0;
  int high = list.length - 1;
  
  while (low <= high) {
    // Calculate the middle index
    int mid = low + ((high - low) ~/ 2);
    
    // Check if the searchKey is present at mid
    if (list[mid] == searchKey) {
      return mid;
    }
    // If searchKey is greater, ignore the left half
    else if (list[mid] < searchKey) {
      low = mid + 1;
    }
    // If searchKey is smaller, ignore the right half
    else {
      high = mid - 1;
    }
  }
  
  // If the searchKey is not present in the list
  return -1;
}
void main() {
  

  List<int> sortedList = [2, 3, 4, 10, 40];
  int searchKey = 10;
  
  int result = binarySearch(sortedList, searchKey);
  
  if (result != -1) {
    print("Element found at index: $result");
  } else {
    print("Element not found in the list");
  }
}

Output

Element found at index: 3


Conclusion

You’ve have successfully build a dart code that utilize Data Structure & Algorithms (DSA). By implement DSA in Dart we can create a super powerful dart application that can solve complex problems very efficiently.

Redux 5 Interview Questions with answers

0
redux interview questions with answers
redux interview questions with answers

Hi Guy’s In this Article let’s check out 5 Interview Question that are very important and can be asked to you in your next Interview.

Redux: Commonly used while build Reach Application, Redux Help you in managing the state of the application in a more structured and scalable way. It helps in maintaining the state of the entire application in a single source of storage, making it easier to manage, debug, and test while building application using React.

5 Interview Question with Answer on Redux

1. What are the 3 Core Principles of Redux?

  • Single Source of Truth.
  • State is read-only.
  • Changes are made with pure functiions.

2. How Does Redux handle Asynchronous Operations?

Redux is an synchronous, but you can handle asynchronous operations using middleware like Redux Thunk & Redux Saga.

3. Implement Server-Side Rendering with Redux?

  1. Create a Redux Store on the server for each request.
  2. Dispatch actions to fetch and populate data.
  3. Render the app to a string with the server store.
  4. Embed the initial state in the HTML response.
  5. Rehydrate the state on the client with the initial state.

4. How can you Persist the Redux State Across Sessions?

To persist the Redux state, you can use middleware like redux-persist.

5. Best practices for Structuring Redux Applications?

  1. Organize files by feature/module.
  2. Colocate selectors & actions with reducers.
  3. Combine actions, reducers and types in single file.
  4. Use entities & ids to avoid deeply nested structures.

Improve performance of your Flutter apps – Future.wait()

0
future wait
future wait

Hi Guy’s, Welcome to Proto Coders Point. In the changing world of mobile App development, App Performance plays an crucial role that can build you app business or break the plan if performance is weak. As a flutter developer where we build mobile application for cross platform like mobile, android, ios or desktop, where we need to focus of app performance in multiple operations simultaneously, can be making a API call to fetch data, executing database transaction or carrying out complex computations.

Sequential Execution of program

The most common mistake many application developer does is exciting an operation in a sequence, may be he is using async, He make mistake by executing operation one after another, which will lead into slowing down the app or user might see lag in UI while an operation is fetching data and will be poor user experience.

The Solution is concurrent execution of operations

Future.wait() is a game-changer, when it comes handling multiple asynchronous operations concurrently. By using Future.wait() we can execute multiple futures at the same time, Therefore this will reduce the over all waiting time and will lead to improving app performance.

Code Example – without using Future.wait()

Below code is by executing operation sequentially one by one.

The below code will take 4 seconds to completely run the program

void main() async{
  var data1 =  await delayedNumber();
  print(data1);
  // Here there is a await of 2 second
  var data2 = await delayedString();
  // Here there is a await of 2 second
   print(data2);
 // totally it take 4 seconds to completely run the program
}

Future<int> delayedNumber() async{
   await Future.delayed(Duration(seconds:2));
   
   return 1;
}

Future<String> delayedString() async{
  await Future.delayed(Duration(seconds:2));
  return 'Results';
}

Code Example – using Future.wait()

void main() async{
  var data = await Future.wait([
     delayedNumber(),
     delayedString()
]);
  
  print(data[0]); // [2,results]
}

Future<int> delayedNumber() async{
   await Future.delayed(Duration(seconds:2));
  
   return 1;
}

Future<String> delayedString() async{
  await Future.delayed(Duration(seconds:2));
  return 'Results';
}

Here by using By executing multiple futures concurrently, Future.wait() reduces the overall waiting time for operations. This is particularly useful for tasks that are independent of each other, such as fetching data from different APIs or performing unrelated computations.

What’s new in flutter 3.22

0
flutter 3.22
flutter 3.22

Hi Guys, Welcome to Proto Coders Point. In this Flutter Article let’s check out what’s new with flutter version 3.22.

Flutter 3.22

Performance Enhancements

Web Assemble Support: This stable release brings WebAssembly support to Flutter for improved web app performance.

Vulkan Backend for Impeller: This provides smoother graphics and better performance on Android devices.

Platform View Performance on IOS: Except smoother scorlling and overall performance for platform views on iOS devices.

Firebase Integration: Their was an issue with Firebase integration which is been been resolved now, ensuring smoother backend services like authentication, real-time databases, and analytics​.

Improved Developer Workflow

Widget State Properties: This simplifies widget state management by separating state logic from the build method

Dynamic View Sizing: This enhances layout responsiveness by allowing widgets to determine their size based on available space.

Improved form Validation: This streamlines user input handling with better error handling and validation capabilities.

UI Components and Material Design: Updates include improved behavior of Search Anchor Tag, fixes for the visibility of clear buttons in search views, and enhanced scrolling capabilities in disabled TextFields. Padding issues in TextFields under Material 3 have also been resolved​.

Other additional Improvement in flutter 3.22

Flavor-Conditional Asset Bundling: This allows you to selectively bundle assets based on different app flavors.

Gradle Kotlin DSL Support: This improves Gradle build script editing for projects using the kotlin DSL.

How to convert string & numbers into Byte Array in Flutter Dart

0
convert string into byte in flutter dart
convert string into byte

Hi Guy’s Welcome to ProtoCodersPoint, In this Article will checkout How can we convert String or Number (May be it Integer or double) to a byte array (i.e. A List of bytes) in Dart.

Converting strings & number into byte Array (or also know as byte lists) in flutter dart we can make use of different built-in methods provided within dart language.

Converting a String to a Byte Array

    I found out 3 ways by which we can convert a given String into a byte array by using dart language.

    using utf8.encode() method

    you can use the utf8.encode method from the dart:convert library. This method converts a string into a list of bytes.

    import 'dart:convert';
    
    void main() {
      String input = "Hello, Flutter Developer!";
      List<int> byteArray = utf8.encode(input);
      print(byteArray);
    }
    

    output

    [72, 101, 108, 108, 111, 44, 32, 70, 108, 117, 116, 116, 101, 114, 32, 68, 101, 118, 101, 108, 111, 112, 101, 114, 33]
    

    Using .codeUnits property of the String class

    Yes, the codeUnits property of the String class in Dart returns a list of UTF-16 code units. This is another way to convert a string to a byte array, although the result will be in UTF-16 encoding rather than UTF-8.

    import 'dart:convert';
    
    void main() {
      String text = 'protoCodersPoint.com';
      List<int> bytes = text.codeUnits;
      print(bytes);
    }
    

    Output

    [112, 114, 111, 116, 111, 67, 111, 100, 101, 114, 115, 80, 111, 105, 110, 116, 46, 99, 111, 109]
    

    What is the Differences Between UTF-16 byte Encoding and UTF-8 Encoding

    • UTF-16: Each character is typically represented by two bytes. The codeUnits property directly provides these values.
    • UTF-8: Each character can be represented by one to four bytes, depending on the character. The utf8.encode method handles this conversion.

    Using the runes property of the String class

    In Dart Language the .runes property of the String class provides a way to access the Unicode code points of a string. This is method is very useful while dealing with characters outside the Basic Multilingual Plane (BMP) that cannot be represented by a single UTF-16 code unit.

    void main() {
      String input = "Hello, 🌍!";
      Iterable<int> runeList = input.runes;
      print(runeList); // Output: (72, 101, 108, 108, 111, 44, 32, 127757, 33)
      
      // Convert to a list if needed
      List<int> runeArray = runeList.toList();
      print(runeArray); // Output: [72, 101, 108, 108, 111, 44, 32, 127757, 33]
    }
    

    Output

    (72, 101, 108, 108, 111, 44, 32, 32, 80, 114, 111, 116, 111, 32, ..., 115, 33)
    
    [72, 101, 108, 108, 111, 44, 32, 32, 80, 114, 111, 116, 111, 32, 67, 111, 100, 101, 114, 115, 33]


    Converting a Number into a Byte Array

    In dart, to convert a numbers into a byte array, We have a in-built class i.e. ByteData that comes from dart:typed_data library. This class help you working with low-level data types & convert them into byte array. below is a example:

    converting a integer to Byte Array

    import 'dart:typed_data';
    
    void main() {
      int number = 123456;
      ByteData byteData = ByteData(4);
      byteData.setInt32(0, number);
      List<int> byteArray = byteData.buffer.asUint8List();
      print(byteArray); // Output: [64, 226, 1, 0]
    }
    

    Converting a double to a Byte Array

    import 'dart:typed_data';
    
    void main() {
      double number = 123.456;
      ByteData byteData = ByteData(8);
      byteData.setFloat64(0, number);
      List<int> byteArray = byteData.buffer.asUint8List();
      print(byteArray); // Output: [119, 190, 247, 87, 141, 235, 94, 64]
    }
    

    Conclusion

    String to Byte Array: We can make use of utf8.encode or codeUnits for UTF-16 Encoding.

    Number to Byte Array: We can use ByteData with appropriate methods like setInt32 for integers and setFloat64 for doubles.