flutter
/

Dart Variables and Data Types – Complete Guide

Last Sync: Today

On this page

13
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart Variables and Data Types – Complete Guide

What are Variables in Dart?

A variable is a named storage location in memory that holds a value. In Dart, variables can store different types of data such as numbers, text, booleans, and more. Dart is a statically typed language, but it also supports type inference, making variable declaration flexible and concise.

Declaring Variables

You can declare a variable using the var keyword, or by explicitly specifying the type. Once a variable is declared with a type, it can only hold values of that type.

DARTRead-only
1
void main() {
  var name = 'Alice';        // type inferred as String
  int age = 30;               // explicitly typed integer
  double height = 5.8;        // double (floating‑point)
  String city = 'New York';   // explicit String
  bool isStudent = false;     // boolean
  
  print('$name is $age years old, lives in $city.');
}

Built‑in Data Types

Dart provides several core data types:

    • int: Integer numbers (e.g., 42, -10)
    • double: Floating‑point numbers (e.g., 3.14, -0.5)
    • num: Generic number type (can be int or double)
    • String: Sequence of characters ('Hello', "Dart")
    • bool: Boolean values (true or false)
    • List: Ordered collection (similar to arrays)
    • Map: Key‑value pairs
    • dynamic: Can hold any type (disables type checking)

Type Inference with var

When you declare a variable with var, Dart infers its type from the initial value. After inference, the variable's type is fixed and cannot be changed.

DARTRead-only
1
void main() {
  var message = 'Hello';   // inferred as String
  // message = 123;        // Error: can't assign int to String
  
  var count = 10;          // inferred as int
  count = 15;              // OK – still int
}

Explicit Type Declaration

You can also specify the type explicitly. This is useful when you want to be clear about the intended type or when you declare a variable without an initial value.

DARTRead-only
1
void main() {
  String greeting;        // declared without initial value
  greeting = 'Hi';        // assigned later
  
  int a, b;               // multiple declarations
  a = 5;
  b = 10;
}

The dynamic Type

If you need a variable that can change type at runtime, use dynamic. However, overusing dynamic defeats the purpose of static type checking and should be avoided unless absolutely necessary.

DARTRead-only
1
void main() {
  dynamic flexible = 'Hello';
  print(flexible);          // Hello
  flexible = 42;            // now it's an int
  print(flexible);          // 42
}

Final and Const – Immutable Variables

Use final or const for variables that should not change after being set. final is set once at runtime; const is a compile‑time constant.

DARTRead-only
1
void main() {
  final name = 'Alice';        // set once
  // name = 'Bob';              // Error: can't change final
  
  const pi = 3.14159;           // compile‑time constant
  // pi = 3.14;                  // Error
  
  // `const` requires compile‑time values
  const double gravity = 9.8;    // OK
  // const now = DateTime.now(); // Error: not compile‑time constant
}

Null Safety in Dart

Dart supports sound null safety. By default, variables cannot be null. To allow a variable to hold null, add a ? after the type.

DARTRead-only
1
void main() {
  int? nullableInt;          // can be null
  nullableInt = null;         // allowed
  
  String? name;               // nullable
  print(name?.length);         // safe access: prints null
  
  // String nonNullable = null; // Error – can't assign null
}

Default Values

Uninitialized variables with a nullable type have the default value null. For non‑nullable types, you must provide an initial value before use.

DARTRead-only
1
void main() {
  int? a;        // default null
  print(a);      // null
  
  // int b;       // Error: non‑nullable must be initialized
  int b = 0;     // OK
}

Type Conversion

You can convert between types using built‑in methods like toString(), parse(), etc.

DARTRead-only
1
void main() {
  int number = 42;
  String numberStr = number.toString();   // '42'
  
  double pi = 3.14;
  int piInt = pi.toInt();                  // 3 (truncates)
  
  String text = '123';
  int parsed = int.parse(text);            // 123
}

Naming Conventions

    • Variable names should use camelCase (e.g., firstName, totalAmount).
    • Class names use PascalCase (e.g., Person, ShoppingCart).
    • Constants (with const) often use lowerCamelCase (no special prefix).
    • Avoid using single‑letter names except for trivial loop counters (i, j).
    • Names should be descriptive and meaningful.

Complete Example

DARTRead-only
1
void main() {
  // Various variable declarations
  String firstName = 'John';
  String lastName = 'Doe';
  int age = 25;
  double height = 5.9;
  bool isEmployed = true;
  
  // Using var
  var city = 'New York';
  var score = 95.5;
  
  // Nullable variable
  String? middleName;
  
  // Final constant
  final country = 'USA';
  const double pi = 3.14159;
  
  // Printing values
  print('$firstName $lastName is $age years old.');
  print('Lives in $city, $country.');
  print('Height: $height, Employed: $isEmployed');
  print('Score: $score, Pi: $pi');
}

Key Takeaways

    • Variables store data and have a type.
    • Use var for type inference, or explicitly specify the type.
    • Dart has built‑in types: int, double, String, bool, List, Map.
    • Use final for runtime constants and const for compile‑time constants.
    • Null safety prevents null errors – use ? for nullable types.
    • Always follow naming conventions for clean code.

Try it yourself

void main() {
  // Try declaring variables of different types
  var name = 'Dart Learner';
  int year = 2025;
  double version = 3.0;
  bool isFun = true;
  
  print('Hello, $name!');
  print('Year: $year, Version: $version');
  print('Is Dart fun? $isFun');
}

Test Your Knowledge

Q1
of 4

Which keyword is used to declare a variable whose type is inferred from its initial value?

A
let
B
dynamic
C
var
D
auto
Q2
of 4

What is the output of this code? void main() { var x = 10; x = 'hello'; print(x); }

A
10
B
hello
C
Error
D
null
Q3
of 4

Which of the following correctly declares a nullable integer?

A
int? number;
B
int number?;
C
nullable int number;
D
int? number = 0;
Q4
of 4

What is the difference between `final` and `const`?

A
There is no difference
B
`const` is set at runtime, `final` at compile time
C
`final` is set once at runtime, `const` is a compile‑time constant
D
`final` can be reassigned, `const` cannot

Frequently Asked Questions

What is the difference between `var` and `dynamic`?

var declares a variable with a fixed type inferred from the initial value. Once inferred, the type cannot change. dynamic disables type checking, allowing the variable to hold any type and change at runtime. Prefer var over dynamic for type safety.

Can I change the type of a variable declared with `var`?

No. After type inference, the variable's type is fixed. For example, var x = 10; makes x an int; you cannot later assign a String to it.

When should I use `final` vs `const`?

Use final for variables that are set once at runtime (e.g., a value from a calculation or user input). Use const for compile‑time constants that never change (e.g., pi = 3.14). const variables are implicitly final.

How do I make a variable nullable?

Add a ? after the type: int? nullableInt;. This allows the variable to hold either an integer or null. Without ?, the variable is non‑nullable and cannot be null.

What is type inference?

Type inference is Dart's ability to deduce the type of a variable from its initial value when you use var. For example, var name = 'Alice'; infers String. This keeps code concise while maintaining static typing.

What are the default values of uninitialized variables?

For nullable types, the default value is null. Non‑nullable types must be initialized before use; they have no default value and the compiler enforces initialization.

How do I convert a string to an integer?

Use int.parse(string) or int.tryParse(string) (which returns null if parsing fails). For example: int.parse('123') returns 123.

Can I use `var` without an initial value?

No. var requires an initializer to infer the type. If you need a variable without an initial value, declare it with an explicit type (e.g., int x;).

Previous

dart syntax

Next

dart operators

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.