OneBite.Dev - Coding blog in a bite size

Assign Multiple Variables In Dart

Code snippet for how to Assign Multiple Variables In Dart with sample and detail explanation

Dart is a client-optimized language often used for web development. It also forms the foundation of Flutter, a cross-platform development solution from Google. This article will discuss how you can easily assign multiple variables in Dart.

Code snippet for Assigning Multiple Variables

Here is a simple way to create and assign multiple variables in Dart.

void main() {
  var a, b, c;

  a = 5;
  b = 'Hello';
  c = true;

  print(a); // Output: 5
  print(b); // Output: Hello
  print(c); // Output: true
}

By running the above code, you will get the values of variables a, b, and c as 5, Hello and true respectively.

Code Explanation for Assigning Multiple Variables

To begin, you’ll notice a keyword var at the start of the code. In Dart, the var keyword is used to declare a variable without explicitly defining its type. The Dart language is type-safe, meaning that values always have a specific type, but type declarations are optional because of type inference.

Next, we have three variable names: a, b, and c. They are separated by commas, implying that we’re declaring multiple variables at once. These variables are undefined at this point, they don’t have any value yet.

Following these declarations, we assign values to these variables: a is assigned the value of 5, b is assigned the string ‘Hello’, and c is assigned the boolean value true. These assignments are done with the use of the = operator.

Finally, we print the values of the variables. The print() function in Dart sends the specified value to the console, which is how we can check the assigned values of the variables a, b, and c.

Bear in mind that in Dart, you can freely assign different types of values to variables declared using var, but once a value has been assigned, the variable becomes locked to that type. If you try to assign a different type of value later in your code, you’ll get an error. This is because Dart uses type inference to determine variable types, and treats them as such from their first assignment onwards.

dart