Home Blog Page 3

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.


    Ways to Iterate through object JavaScript – Object Iteration

    0
    iterate through object javascript
    iterate over object javascript

    Objects in JavaScript are data stored in string type that are stored as key-value pair. One of the important concept working with objects is iterations, Iteration in other words is traversing through the properties of object. In this JS article let’s checkout different ways to iterate through object in javascript.

    referral Object

    const person = {
        firstName: "John",
        lastName: "Doe",
        age: 30,
        email: "john.doe@example.com",
        address: {
            street: "123 Main St",
            city: "Anytown",
            state: "CA",
            zipCode: "12345"
        },
        hobbies: ["reading", "traveling", "gardening"],
        isActive: true
    };
    

    JavaScript Methods to Iterate an Object

    1. for…in Loop:

    The for...in, javascript loop through object goes through all the enumerable elements/properties of an object, and also those that are inherited from its prototype chain.

    for (let key in obj) {
        console.log(key, obj[key]);
    }
    

    result:

    firstName: John
    lastName: Doe
    age: 30
    email: john.doe@example.com
    address: [object Object]
    hobbies: reading,traveling,gardening
    isActive: true

    2. Object.keys() Method

    The Object.keys() method returns all the keys items in an array.

    const keys = Object.keys(person);
    console.log(keys);
    

    result

    [
      'firstName',
      'lastName',
      'age',
      'email',
      'address',
      'hobbies',
      'isActive'
    ]

    3. Object.values() Method

    The Object.values() method returns all the values items in an array.

    const values = Object.values(obj);
    values.forEach(value => {
        console.log(value);
    });
    

    result

    [
      'John',
      'Doe',
      30,
      'john.doe@example.com',
      {
        street: '123 Main St',
        city: 'Anytown',
        state: 'CA',
        zipCode: '12345'
      },
      [ 'reading', 'traveling', 'gardening' ],
      true
    ]

    4. Object.entries() Method

    The Object.entries() method returns a new array which contains all the value in key-value pairs in a form of array, example below.

    const entries = Object.entries(person);
    console.log(entries);

    result:

    [
      [ 'firstName', 'John' ],
      [ 'lastName', 'Doe' ],
      [ 'age', 30 ],
      [ 'email', 'john.doe@example.com' ],
      [
        'address',
        {
          street: '123 Main St',
          city: 'Anytown',
          state: 'CA',
          zipCode: '12345'
        }
      ],
      [ 'hobbies', [ 'reading', 'traveling', 'gardening' ] ],
      [ 'isActive', true ]
    ]
    

    Note:

    In JavaScript the order of iteration is not guaranteed in JS Object.

    The loops methods like for...in can loop only enumerable properties but not non-enumerable properties in object. If you want to iterate object properties that are non-enumerable then you need to used methods like Object.getOwnPropertyName or Reflect.ownKeys().

    Flutter Dart `then` vs `whenComplete` vs `catchError`

    0
    flutter dart then vs whenComplete vs catchError
    flutter dart then vs whenComplete vs catchError

    Hi Guy’s, Welcome to Proto Coders Point, In this Flutter Article let’s then whenComplete and catchError in Flutter Dart.

    In Flutter/Dart Programming language, We make use of then, whenComplete, and catchError methods are used with Futures to handle asynchronous task operation in flutter dart.

    1. then : Used to handle the success completion of a Future and then access the result.
    .then() only works if the Future task like fetching data from server is success (without any errors).

    2. whenComplete : Used to execute a callback function whenever the Future completes, regardless of success or error. Means even if there is any error whenComplete will get executed. It’s similar to finally this is like default result.

    3. catchError: Used to handles error caught while fetching Future result or Future logic has some error in it.

    Code Example to demonstrate then,whenComplete and catchError with Future in Dart:

    import 'dart:async';
    
    void main() {
    
      // Example Future that resolves after 2 seconds
      Future<String> fetchData() {
        return Future.delayed(Duration(seconds: 2), () => "Data fetched successfully");
      }
    
      // Example Future that throws an error after 3 seconds
      Future<String> simulateError() {
        return Future.delayed(Duration(seconds: 3), () => throw Exception("Error occurred"));
      }
    
      // Using then to handle successful completion
      fetchData().then((data) {
        print("Data: $data");
      }).catchError((error) {
        print("Error fetching data: $error");
      });
    
      // Using whenComplete to execute code regardless of success or failure
      simulateError().then((data) {
        print("Data: $data");
      }).catchError((error) {
        print("Error fetching data: $error");
      }).whenComplete(() {
        print("Completed");
      });
    }
    

    OutPut

    Data: Data fetched successfully
    Error fetching data: Exception: Error occurred
    Completed
    

    Understanding JavaScript’s this Keyword with call() Method

    0
    This keyword in javascript, call() method example.
    This keyword in javascript, call() method example.

    Hi Guy’s Welcome to Proto Coders Point, In this article let’s understand 'this' keyword in JavaScript and how it plays an important role in JavaScript.

    The 'this' keyword is the context in which function it is defined. It is dynamically refers to object that is currently executing the function.

    For better understanding let’s refer below code and learn how this keyword context works and how to make use of call() method in JavaScript that allows borrowing methods from one object to another.

    Source Code

    let obj1 = {
        firstName: "Rajat",
        lastName: "Palankar",
        fullName : function(){
            console.log(this.firstName + " " + this.lastName);
        }
    }
    
    let obj2 = {
        firstName: "Suraj",
        lastName: "Somanche",
    }
    
    obj1.fullName(); //"Rajat Palankar"
    
    obj1.fullName.call(obj2); // "Suraj Somnache"

    In Above JS Snippet Code, we have two objects, named obj1 and obj2, each of this object containing key/Value pair properties firstName and lastName. With this obj1 has an additional method called fullName which simply logs the full name by concatenating firstName and lastName.

    Now, let’s check out how the this keyword operates in the context within this fullName method.

    When fullName() is called on obj1 by doing something like: obj1.fullName(), here this context refers to the obj1 object itself. Thus, this.firstName will return us “Rajat” and this.lastName will return us “Palankar”, and concat it and print “Rajat Palankar” on screen.

    But what if we want to reuse the fullName method that is defined in obj1 but this context should point to obj2 object? This is when we can make use of call() method in javascript.

    The call() method allows us to invoke a function with a specific this context. Here’s how it works:

    obj.fullName.call(obj2);
    

    The line, obj.fullName refers to the fullName method of obj, and call(obj2) is used to invoke obj1 with obj2 as it’s this context. So, Now this context is refering to obj, In this way now, this.firstName inside the fullName function of obj1 is now refers to obj2.firstName and this.lastName refers to obj2.lastName. Consequently, “Suraj Somanche” is logged to the console.