Skip to main content

Command Palette

Search for a command to run...

Rules for Declaring Variables and Understanding Data Types in Dart

Updated
4 min read

When working with any programming language, understanding how to declare variables and work with data types is fundamental. Dart, a versatile and efficient language, offers a simple yet powerful way to handle these concepts. Let’s explore the rules and guidelines for declaring variables and working with data types in Dart.

1. Declaring Variables in Dart

In Dart, variables can be declared using the var, final, const, or specific type keywords (like int, String, etc.). Below are the primary rules and recommendations:

1.1 Using var

  • The var keyword allows Dart to infer the type of the variable at compile time based on the initial value.

  • Once a variable’s type is inferred, it cannot be reassigned to a value of a different type.

      var name = "John"; // Dart infers 'String' as the type
      // name = 25; // This will cause a type error
    

    1.2 Using final

  • A variable declared with final can only be set once.

  • The value is mutable if it’s an object, but the variable itself cannot be reassigned.

      final city = "Chennai";
      // city = "Mumbai"; // Error: Cannot change the value of a final variable
    

    1.3 Using const

  • The const keyword is used for compile-time constants.

  • Variables declared with const must be initialized with a constant value.

  • Unlike final, objects declared as const are immutable.

  •   const pi = 3.14;
      // pi = 3.14159; // Error: Cannot reassign a const variable
    

    1.4 Specifying Data Types

    • Variables can be explicitly declared with their data types, ensuring type safety.

        int age = 25;
        String language = "Dart";
        bool isActive = true;
      

      2. Rules for Naming Variables

      • Variable names must start with a letter (a-z, A-Z) or an underscore (_).

      • Names cannot begin with a number.

      • Only alphanumeric characters and underscores are allowed.

      • Dart is case-sensitive, so Name and name are treated as different variables.

      • Avoid using reserved keywords as variable names (e.g., class, return, if).

Valid examples:

        int studentAge;
        var _score;
        String firstName;

Invalid examples:

  •   int 2count; // Starts with a number
      var class;  // Uses a reserved keyword
    

    3. Data Types in Dart

    Dart is a statically typed language, which means the type of a variable is determined at compile time. Here’s an overview of the commonly used data types:

    3.1 Numbers

    • int: Represents whole numbers.

    • double: Represents fractional numbers.

    •   int age = 30;
        double temperature = 98.6;
      

      3.2 Strings

      • Strings are sequences of characters enclosed in single or double quotes.
            String greeting = 'Hello, Dart!';
            String multiLine = """
            This is a
            multi-line string.
            """;

3.3 Booleans

  • Booleans represent true or false values.

    3.4 Lists (Arrays)

    • Lists are ordered collections of items.
                List<int> numbers = [1, 2, 3, 4, 5];

3.5 Maps

  • Maps are key-value pairs.
                Map<String, int> scores = {
                  'Alice': 90,
                  'Bob': 85
                };

3.6 Dynamic

  • The dynamic type allows a variable to hold any type of value. However, excessive use of dynamic can lead to type safety issues.
                dynamic variable = 100;
                variable = "Now I'm a string";

4. Type Safety and Null Safety

Dart ensures type safety, and with the introduction of null safety, variables cannot have a null value unless explicitly declared as nullable using ?.

                String? nullableName;
                nullableName = null; // Allowed

                String nonNullableName = "John";
                // nonNullableName = null; // Error

5. Best Practices for Declaring Variables

  • Use final or const wherever possible to make variables immutable.

  • Prefer specifying types explicitly for better readability and maintainability.

  • Use meaningful variable names that describe their purpose.

  • Avoid overusing dynamic unless absolutely necessary.


By following these rules and understanding Dart’s data types, you can write cleaner, safer, and more efficient code. Mastering these basics will lay a solid foundation for your Dart programming journey.

More from this blog

S

Suneel D.K

25 posts

Learn Flutter and Dart with easy tutorials and YouTube videos! Master app development with tips, tricks, and detailed guides for beginners and pros alike. Start building today!