free geoip
63

Dart Variables and Data Types with Examples

Understanding variables and data types is the foundation of learning Dart programming. Dart is a client-optimized language used to develop…

Understanding variables and data types is the foundation of learning Dart programming. Dart is a client-optimized language used to develop mobile, desktop, and web apps, most commonly with the Flutter framework.

Dart variables and data types

What Are Variables in Dart?

In Dart, variables are used to store data. You can declare a variable using var, a specific data type (like int, String), or use the final and const keywords for fixed values.

Dart Data Types Overview

Here are the most commonly used data types in Dart:

  • int: Stores integer values
  • double: Stores decimal values
  • String: Stores text
  • bool: Stores true or false
  • List: Stores an ordered collection
  • Map: Stores key-value pairs
  • dynamic: Can store any type and is resolved at runtime

Example Code

void main() {
  // Integer
  int age = 25;
  
  // Double
  double height = 5.9;

  // String
  String name = 'Alice';

  // Boolean
  bool isLoggedIn = true;

  // List
  List<String> fruits = ['Apple', 'Banana', 'Mango'];

  // Map
  Map<String, String> capitalCities = {
    'USA': 'Washington, D.C.',
    'India': 'New Delhi'
  };

  // Dynamic type
  dynamic variable = 'Hello';
  variable = 100; // allowed due to dynamic

  print('Name: $name, Age: $age');
  print('Fruits: $fruits');
  print('Capital of USA: ${capitalCities['USA']}');
}

This code demonstrates various data types and how to use them effectively in Dart programming.

Pro Tips:

  • Use final if a variable’s value won’t change.
  • Use const for compile-time constants.
  • Prefer specific types (int, String, etc.) for better readability and type safety.

When to Use Dynamic?

Use dynamic only when you need flexibility, such as when parsing JSON data or interacting with unknown types.

Learn More

You can read the full Dart documentation on variables and types here.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *