Category: Coding & Scripting

FutureBuilder: handle multiple futures in a single widget

By default, FutureBuilder provides a single future parameter that handles a single Future. For multiple Futures, we can combine them into a single Future using Future.wait. Here’s a step-by-step guide on how to do this:

Create a list of Future objects

Create a list of Future objects that represent the asynchronous operations you want to perform. For example, let’s assume you have two futures:

Future<String> fetchFirstData() async {
  // Simulate a network request or other asynchronous operation.
  await Future.delayed(Duration(seconds: 2));
  return "First Data";
}

Future<int> fetchSecondData() async {
  // Simulate another asynchronous operation.
  await Future.delayed(Duration(seconds: 3));
  return 42;
}

Combine the futures using Future.wait

Use the Future.wait method to combine the individual futures into a single future. Future.wait takes a list of futures as an argument and returns a single future that completes when all the input futures have completed.

Future<void> fetchData() async {
  await Future.wait([fetchFirstData(), fetchSecondData()]);
}

Create a FutureBuilder widget

Now, use the FutureBuilder widget to handle the combined future and display the results in your widget tree. You can place this widget in your build method.

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: fetchData(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          // Use the results from the futures here.
          if (snapshot.hasError) {
            return Text("Error: ${snapshot.error}");
          } else {
            return Column(
              children: [
                Text("First Data: ${snapshot.data[0]}"),
                Text("Second Data: ${snapshot.data[1]}"),
              ],
            );
          }
        } else {
          // While waiting for the futures to complete, you can show a loading indicator or placeholder.
          return CircularProgressIndicator();
        }
      },
    );
  }
}

In the code above, we use the snapshot to check the connectionState. When the connectionState is ConnectionState.done, it means that both futures have completed. You can access the results using snapshot.data.

Remember to replace the fetchFirstData and fetchSecondData functions with your actual asynchronous operations. This example demonstrates how to use FutureBuilder to handle multiple futures in a single widget in Flutter.

Foto von Tomasz Frankowski auf Unsplash

 

mysqldump: how to use a specific port

To use a specific port with the mysqldump command, you can provide the --port (or -P) option followed by the port number you want to use. The --port option specifies the TCP/IP port number to use when connecting to the MySQL server.

When using -P remember to use an uppercase P, because the lowercase option -p refers to the password.

Here’s the general syntax of using mysqldump with a specific port:

mysqldump --port=PORT_NUMBER -u USERNAME -p DATABASE_NAME > dump.sql

Replace the following placeholders:

  • PORT_NUMBER: The specific port number you want to use (e.g., 3306).
  • USERNAME: Your MySQL username.
  • DATABASE_NAME: The name of the database you want to dump.
  • dump.sql: The name of the file where you want to save the database dump.

After executing this command, you’ll be prompted to enter your MySQL password. Once you provide the correct password, the mysqldump command will connect to the MySQL server using the specified port and create a dump of the specified database.

Foto von André Carvalho auf Unsplash

 

JavaScript: the differences between escape(), encodeURI(), and encodeURIComponent()

Foto von Markus Spiske auf Unsplash

In JavaScript, escape(), encodeURI(), and encodeURIComponent() are three functions used to encode strings for different purposes. Each function serves a distinct purpose, and it’s essential to understand their differences:

escape()

The escape() function is used to encode a string so that it can be safely included in a URL query string. It encodes special characters, except for alphanumeric characters and the following set of symbols: @*_+-./. The main drawback of escape() is that it does not encode all characters, and it’s considered deprecated in favor of encodeURIComponent().

Example:

const originalString = "Hello, World!";
const encodedString = escape(originalString);
console.log(encodedString); // "Hello%2C%20World%21"

encodeURI()

The encodeURI() function is used to encode a complete URI (Uniform Resource Identifier) but leaves the special characters used in the query string (?, &, =, etc.) untouched. It is primarily used to encode the main part of a URL, such as the protocol, domain, and path.

Example:

const originalURI = "https://www.example.com/my page.html?name=John Doe";
const encodedURI = encodeURI(originalURI);
console.log(encodedURI); // "https://www.example.com/my%20page.html?name=John%20Doe"

encodeURIComponent()

The encodeURIComponent() function is used to encode a component of a URI, such as a query parameter, fragment identifier, or any part that needs to be included in the query string. Unlike encodeURI(), this function encodes all special characters to ensure they are safely passed as parameters in a URL.

Example:

const originalParameter = "John Doe";
const encodedParameter = encodeURIComponent(originalParameter);
console.log(encodedParameter); // "John%20Doe"

In summary

Use escape() for encoding a string to be safely included in a query string, but it’s deprecated and not recommended for general use.

Use encodeURI() for encoding a complete URI (protocol, domain, path) but not the query string parameters.

Use encodeURIComponent() for encoding individual components (e.g., query parameters) of a URI to ensure all special characters are encoded properly. This is the most commonly used encoding function for URLs.

Foto von Markus Spiske auf Unsplash

PHP: when should I use ‘self’ and when should I use ‘$this’?

In PHP, the keyword $this is used to refer to the current instance of the class, while the keyword self is used to refer to the class itself.

You should use $this when referring to instance-level properties or methods within the same class, such as when accessing a property of the current object or calling a method of the current object.

For example:

class MyClass {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function sayHello() {
        echo "Hello, my name is " . $this->name;
    }
}

$obj = new MyClass("John");
$obj->sayHello(); // output: "Hello, my name is John"

On the other hand, you should use self when referring to static properties or methods within the same class, such as when accessing a static property or calling a static method of the class.

For example:

class MyClass {
    private static $count = 0;

    public function __construct() {
        self::$count++;
    }

    public static function getCount() {
        return self::$count;
    }
}

$obj1 = new MyClass();
$obj2 = new MyClass();
echo MyClass::getCount(); // output: 2

In summary, $this is used for instance-level properties and methods, while self is used for static properties and methods.

PHP: How to check if a string contains a specific word?

You can check if a string contains a specific word in PHP by using the strpos() function, the preg_match() function or the str_contains() function.

Using strpos()

The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found, it returns false. You can use this function to check if a string contains a specific word as follows:

$string = "This is a sample string.";
$word = "sample";

if (strpos($string, $word) !== false) {
    echo "The string contains the word.";
} else {
    echo "The string does not contain the word.";
}

In this example, we first define a string $string and a word $word. Then, we use the strpos() function to check if the $string contains the $word. If the $word is found in the $string, the function will return a position value that is not false, and the output will be “The string contains the word.” Otherwise, the function will return false, and the output will be “The string does not contain the word.”

Using preg_match()

The preg_match() function searches a string for a pattern and returns true if the pattern is found, and false otherwise. You can use this function to check if a string contains a specific word as follows:

$string = "This is a sample string.";
$word = "/sample/";

if (preg_match($word, $string)) {
    echo "The string contains the word.";
} else {
    echo "The string does not contain the word.";
}

Using str_contains()

The str_contains() method is available in PHP 8 and higher versions. You can use this method to check if a string contains a specific word as follows:

$string = "This is a sample string.";
$word = "sample";

if (str_contains($string, $word)) {
    echo "The string contains the word.";
} else {
    echo "The string does not contain the word.";
}

Performance Comparison

When comparing the performance of those three methods, we get the following result:

strpos()1.37e-7 seconds = 0.137 micro seconds
preg_match()1.54e-7 seconds = 0.154 micro seconds
str_contains()1.28e-7 seconds = 0.128 micro seconds

So the new method str_contains() (for PHP 8.0 or higher) is the fastest one.

For the results, the mean execution time in a loop with 1,000,000 cycles was calculated for each method.

Dart: What is the difference between the “const” and “final” keywords?

In Dart, both const and final are used to declare variables that can’t be reassigned after they’re initialized. However, there are some differences between them:

  1. const is used to declare a compile-time constant. The value of a const variable must be known at compile time. When you create an object using const, Dart ensures that there is only one instance of that object. const can be used to create constant values of built-in types, as well as classes and collections that are also const.
  2. final is used to declare a variable that can only be set once. It doesn’t have to be initialized at compile-time, but once it’s initialized, it can’t be changed. final can be used to create non-constant values of built-in types, as well as classes and collections that are not const.

In general, use const when you have a value that will never change and you want to ensure that only one instance of it exists, and use final when you have a value that won’t change but can’t be known at compile time.

Example Usage

class MyClass {
  final int a;
  static const int b = 10;

  MyClass(this.a);

  void printValues() {
    print('a: $a');
    print('b: $b');
  }
}

void main() {
  final obj = MyClass(5);
  obj.printValues();
}

In this example, we have a class MyClass with two member variables a and b. a is declared as final, which means that it can only be assigned once, either in the constructor or when it’s declared. b is declared as static const, which means that it’s a compile-time constant and there is only one instance of it across all instances of the class.

In the constructor of MyClass, we assign the value of a. When we create an instance of MyClass in main(), we pass the value 5 to the constructor, which assigns it to a.

Then, we call the method printValues(), which prints the values of a and b. Since b is declared as static const, we can access it using the class name (MyClass.b) instead of an instance of the class.

Overall, final and const are useful in classes to create immutable values that can’t be changed once they’re initialized. final is used for values that can be initialized at runtime, while const is used for values that can be initialized at compile-time.

Flutter: How to Create a Color from a Hexadecimal Color String

In Flutter, you can create a color from a hexadecimal color string value using the Color class. The Color class takes a 32-bit integer value as an argument, where the first 8 bits represent the alpha channel (transparency) and the remaining 24 bits represent the red, green, and blue channels.

To create a color object from a hexadecimal color string value, you need to pass the value to the Color() constructor. For example, to create the color red, you can use the following code:

Color color = Color(0xFFFF0000);

To create a color from a hexadecimal string value, you need to convert the string to a 32-bit integer value first. Here’s an example of how to do it:

String hexColor = "#FF0000"; // red color
Color color = Color(int.parse(hexColor.substring(1, 7), radix: 16) + 0xFF000000);

In the above code, the substring(1, 7) method is used to remove the “#” character from the hexadecimal color string. The int.parse() method converts the remaining string into a 32-bit integer value using the radix argument, which specifies that the string is in base 16 (hexadecimal). The + 0xFF000000 part adds the alpha channel value of 255 (fully opaque) to the color value.

Colors with Transparency

You can also create colors with transparency using an eight-digit hexadecimal color string value. The first two digits represent the alpha channel, which controls the opacity of the color. For example, to create a semi-transparent red color, you can use the following code:

Color semiTransparentColor = Color(0x80FF0000);

Or for a given string value:

String hexColor = "#FF0000"; // red color
Color semiTransparentColor = Color(int.parse(hexColor.substring(1, 7), radix: 16) + 0x80000000);

Here, 0x80FF0000 is the hexadecimal color value for red with 50% transparency. The first two digits “80” represent the alpha channel, and the remaining six digits represent the color components.

Usage in Widgets

You can now use the color object to set the color of any widget in your Flutter application:

Container(
  color: color,
  child: ...
)

You can also use the color object as a parameter in some widgets, such as the IconButton widget. Here’s an example:

IconButton(
  icon: Icon(Icons.add),
  color: color, 
  onPressed: () {}, 
)

Foto von Ramakant Sharda auf Unsplash

Pecl: fixing “fatal error: ‘pcre2.h’ file not found”

When using pecl to install a PHP extension, I always got a “fatal error: ‘pcre2.h’ file not found” after PHP has been updated. The update was done using brew upgrade php. In my case, this happens when I try to install pcov using:

pecl install pcov

The output was:

In file included from /private/tmp/pear/temp/pcov/pcov.c:26:
/opt/homebrew/Cellar/php/8.2.2/include/php/ext/pcre/php_pcre.h:23:10: fatal error: 'pcre2.h' file not found
#include "pcre2.h"
         ^~~~~~~~~

To fix the issue, make sure you have pcre2 installed:

brew install pcre2

After this, create a symlink to the pcre2.h file:

ln -s /opt/homebrew/Cellar/pcre2/10.42/include/pcre2.h /opt/homebrew/Cellar/php/8.2.2/include/php/ext/pcre/pcre2.h

Make sure, to adjust the versions of pcre2 and php (or any other package where you got the error). In my case it’s PHP version 8.2.2 (see the error message) and pcre2 version 10.42.

After the symlink was created, the installation of pcov finished without errors:

Build process completed successfully
Installing '/opt/homebrew/Cellar/php/8.2.2/pecl/20220829/pcov.so'
install ok: channel://pecl.php.net/pcov-1.0.11
Extension pcov enabled in php.ini

Foto von Scott Rodgerson auf Unsplash.