Home Blog Page 4

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.

    Android Studio system requirements for laptop or PC (New)

    0
    Android Studio system requirements
    Android Studio system requirements

    Hi Guy’s Welcome to Proto Coders Point. In this Article let’s check System requirement to use Android Studio for building Mobile Applications.

    As you know that Android Studio is most popular IDE developed by JetBrains & Google, Which was specially built for Developing Android Application but now is days is been used in all field like Mobile Application development, Desktop Application or Single Codebase application development using Flutter.

    Android Studio is free to use in all the Operating System Like Windows, macOS, Linux and Chrome OS.

    Below are System Requirements to run Android Studio Smoothly.

    Windows System Requirement for Android Studio

    Minimum system requirements:

    • OS: Windows 8/10/11 (64-bit)
    • CPU: 2nd generation Intel CPU (Sandy Bridge) or newer, AMD CPU with support for a Windows Hypervisor
    • Memory: 8 GB RAM
    • Free storage: 8 GB
    • Screen resolution: 1280 x 800

    Recommended system requirements:

    • OS: Windows 10/11 64-bit
    • CPU: Intel Core i5-8400 3.0 GHz or better
    • Memory: 16 GB RAM
    • Free storage: 30 GB (SSD is strongly recommended)
    • Screen resolution: 1920 x 1080

    MacOS System Requirement for Android Studio

    Minimum system requirements:

    • OS: macOS 10.14 (Mojave) or newer
    • CPU: ARM-based chips, or 2nd generation Intel Core or newer with support for Hypervisor.Framework
    • Memory: 8 GB RAM
    • Free storage: 8 GB
    • Screen resolution: 1280 x 800

    Recommended specifications:

    • OS: macOS 10.15 (Catalina)
    • CPU: Intel Core i5-8400 3.0 GHz or better
    • Memory: 8 GB RAM
    • Free storage: 30 GB (SSD is strongly recommended)
    • Screen resolution: 1920 x 1080

    Linux System Requirement for Android Studio

    Minimum system requirements:

    • OS: Any 64-bit Linux distribution that supports Gnome, KDE, or Unity DE
    • CPU: x86_64 CPU architecture; 2nd generation Intel Core or newer, or AMD processor with support for AMD Virtualization (AMD-V) and SSSE3
    • Memory: 8 GB RAM
    • Free storage: 8 GB
    • Screen resolution: 1280 x 800
    • GNU C Library (glibc) 2.19 or later

    Recommend system requirements:

    • OS: Any 64-bit Linux distribution that supports Gnome, KDE, or Unity DE
    • CPU: Intel Core i5-8400 or better
    • Memory: 8 GB
    • Free storage: 20 GB SSD
    • Free resolution: 1920 x 1080
    • GNU C Library (glibc) 2.19 or later

    Chrome OS System Requirement for Android Studio

    Minimum system requirements:

    • CPU: Intel i5 or higher (U series or higher) recommended
    • Memory: 8 GB
    • Free storage: 8 GB
    • Screen resolution: 1280 x 800

    Android Studio system requirements – Conclusion

    When you start Android Studio the CPU power is used the max and if your CPU is less then i3 process it may get utilized fully and can get overloaded. Therefore, It is recommended to use at least Intel Core i5-8400 or Higher for smooth running of android studio and mobile device emulator. For better smooth experience I suggest you to install android studio in SSD.

    Multiple Listview in Flutter

    0
    multiple listview in flutter
    multiple listview in flutter

    Hi Guy’s Welcome to Proto Coders Point. In this Flutter Tutorial will learn How to display Multiple ListViews in Flutter in a single screen where the user can interact with both the list at once.

    Video Tutorial

    Source Code

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/widgets.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Flutter Demo',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key});
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      final fruits = List.generate(100, (index) => "Fruit $index");
      final veg = List.generate(100, (index) => "Veg $index");
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: MediaQuery.of(context).size.width,
                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                child: Text(
                  "Fruits",
                  style: TextStyle(fontSize: 18),
                ),
                color: Colors.blueAccent,
              ),
              Expanded(
                child: ListView.builder(
                    itemCount: fruits.length,
                    itemBuilder: (context, index) {
                      return Container(
                        child: ListTile(
                          title: Text(fruits[index]),
                        ),
                      );
                    }),
              ),
              Container(
                width: MediaQuery.of(context).size.width,
                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                child: Text(
                  "Veg",
                  style: TextStyle(fontSize: 18, color: Colors.white),
                ),
                color: Colors.black,
              ),
              Expanded(
                child: ListView.builder(
                    itemCount: veg.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Text(veg[index]),
                      );
                    }),
              )
            ],
          ),
        );
      }
    }
    

    Code Explanation

    I have generated a list of data that I want to display in listview.

    final fruits = List.generate(100, (index) => "Fruit $index");
    final veg = List.generate(100, (index) => "Veg $index");

    In above snippet code, I have created 2 dummy list of data by using List.generator and I want to display both the list of data into once screen itself, so that user can easily interact with both of then on single screen.

    Then, To display multiple widgets we make use of Column widget to arrange it’s children vertically. In Column widget we place 2 section: one to display fruits and another to display list of vegetables for this we make use of ListView.builder.

    Each ListView.builder is configured with an itemCount property to determine the number of items in the list.

    The itemBuilder property defines a callback function that returns a widget for each item in the list.

    In the provided code, ListTile widgets are used as list items, displaying text based on the content of fruits and veg lists.