Variables In Dart Programming

Variables In Dart Programming

  • In this blog, we will learn about variables in dart. A variable is nothing but the name given to a memory location where we can store a value. To define a variable in dart there are two ways. The first one is we write data type and the second one is to write the "var" keyword before the variable name.

Defining Variable By Writing Data Type

  • In this method, first, the data type is written followed by the variable name. For example, I want to define marks and I will give the value as 75. Now I have defined a variable, named marks and we have 75 as the value stored for this marks variable.
// First method of declaring a variable 
void main() {
  int marks = 75;
  print(marks);
}
  • Now if you pass marks to my print function, you will get 75 as the output. With this example, we can say that dot is a strongly typed language that means we have to define the type while defining a variable, but it is optional and dart can automatically infer the variable types.

Defining Variable By Using Var Keyword

  • Another way of defining a variable is using the 'var' keyword. Now this time let's say we want to define a string. So what we can do is write 'var' and then the variable name. For example, name equals to let's say Abhinav.
// Second method of declaring a variable 
void main() {
  var name = "Abhinav";
  print(name);
}
  • Now we have a new variable named name, and the value for this variable is this string. In dart, we can use a single or a double quote to define a string literal.