Like other languages (C, C++, Java), whenever a variable is created, each variable has an associated data type. In Dart language, there are the types of values that can be represented and manipulated in a programming language.
In this article, we will learn about Dart Programming Language Data Types.
Data Types in Dart
The data type classification is as given below:
Data Type | Keyword | Description |
---|
Number | int, double, num, BigInt | Numbers in Dart are used to represent numeric literals |
Strings | String | Strings represent a sequence of characters |
Booleans | bool | It represents Boolean values true and false |
Lists | List | An ordered list of elements (like arrays in other languages) |
Sets | Set | A list of distinct elements (unsorted) |
Maps | Map | Collection of key-value pairs where keys are unique |
Runes | Runes | Used for manipulating Unicode characters (although characters API is now preferred) |
Symbols | Symbol | It is an identifier symbol, which is primarily utilized in reflection and debugging |
Null | Null | Represents the lack of a value |
1. Number (int, double, num, BigInt)
The number in Dart Programming is the data type that is used to hold the numeric value. Dart numbers can be classified as:
- int: It is used to represent whole numbers (64-bit Max).
- double: It is used to represent 64-bit precise floating-point numbers.
- num: It is an inherited data type of the int and double types.
- BigInt: For very large integers that exceed
int
limits, use BigInt
.
Declaring Integer (int
)
// Method 1: Declaring an integer variable
int age = 25;
// Method 2: Nullable integer declaration
int? count;
// Method 3: Using 'var' keyword (automatically detects type)
// Dart infers it as int
var year = 2024;
Declaring Decimal Numbers (double
)
// Method 1: Explicit declaration
double pi = 3.1415;
// Method 2: Nullable double
double? percentage;
// Method 3: Using 'var' keyword
// Dart infers it as double
var temperature = 36.6;
Using num
for Both Integer and Decimal Values
num value = 10;
// Allowed because 'num' supports both int and double
value = 10.5;
Declaring Large Integers Using BigInt
BigInt bigNumber = BigInt.parse('987654321098765432109876543210');
Below is the implementation of Numbers in Dart:
Dart
// Dart program to demonstrate
// Number Data Type
void main() {
// Declare an integer
int num1 = 2;
// Declare a double value
double num2 = 1.5;
// Print the integer and
// double values
print("$num1");
print("$num2");
// Perform addition
// (int + double results in a double)
var sum = num1 + num2;
// Print the sum of
// num1 and num2
print("Sum = $sum");
}
Output:
2
1.5
Sum = 3.34
2. Strings (String )
It used to represent a sequence of characters. It is a sequence of UTF-16 code units. The keyword string is used to represent string literals. String values are embedded in either single or double-quotes.
Declaring String in Dart:
String str_name;
Below is the implementation of String data type in Dart:
Dart
// Dart program to demonstrate
// String Data Type
void main() {
// Declare and initialize a string
String string = "Geeks for Geeks";
// Declare two separate string variables
String str = 'Coding is ';
String str1 = 'Fun';
// Print the string variable
print(string);
// Concatenate and print the two strings
print(str + str1);
// Output: Coding is Fun
}
Output:
GeeksforGeeks
Coding is Fun
3. Boolean (bool)
It represents Boolean values true and false. The keyword bool is used to represent a Boolean literal in dart.
Declaring Boolean in Dart
bool var_name;
Below is the implementation of Boolean in Dart:
Dart
// Dart program to demonstrate
// Boolean Data Type
void main() {
// Declare a boolean variable
// with a true value
bool val1 = true;
// Declare two string variables
String str = 'Coding is ';
String str1 = 'Fun';
// Compare the two strings
// (returns false)
bool val2 = (str == str1);
// Print boolean values
print(val1); // Output: true
print(val2); // Output: false
}
Output:
true
false
4. Lists (List)
List data type is similar to arrays in other programming languages. A list is used to represent a collection of objects. It is an ordered group of objects.
Declaring List in Dart
There are multiple methods to declare List in Dart as mentioned below:
1. Variable Size List
// Empty growable list (preferred way)
List<int> var_name1 = [];
// Alternative: Declaring a list but not initializing (null safety requires ? if uninitialized)
List<int>? var_name2;
// Another way using List constructor
List<int> var_name3 = List.empty(growable: true);
2. Fixed Size List
Fixed Size doesn't mean that we can't change the size of List, but we have predefined that the List has this much elements while declaring.
// Creates a fixed-size list with default values (0 in this case)
List<int> var_name1 = List<int>.filled(5, 0);
// Generates a fixed-size list where each element is `index * 2`
List<int> var_name2 = List<int>.generate(5, (index) => index * 2);
Below is the implementation of List in Dart:
Dart
void main() {
// Creating a fixed-size list with
// 3 elements, each initialized to "default"
List<String> gfg = List<String>.filled(3, "default");
// Updating elements in the list
// (modifying values is allowed,
// but resizing is not)
gfg[0] = 'Geeks';
gfg[1] = 'For';
gfg[2] = 'Geeks';
// Printing the entire list to
// verify the changes
print(gfg); // Output: [Geeks, For, Geeks]
// Accessing and printing a
// specific element by its index
print(gfg[0]); // Output: Geeks
}
Output:
[Geeks, For, Geeks]
Geeks
5. Sets (Set)
A Set
is an unordered collection of unique elements.
Declaring Set in Dart
// Method 1: Using curly braces
Set<int> uniqueNumbers = {1, 2, 3, 3, 4};
// Method 2: Using Set constructor
Set<String> cities = Set();
cities.add("New York");
cities.add("London");
Below is the implementation of Set in Dart:
Dart
void main() {
// Declaring a Set of Strings containing country names
// Sets in Dart do not allow duplicate values
Set<String> countries = {"USA", "India", "USA"};
// Printing the set
// Since sets store only unique values, "USA" appears only once
print(countries);
// Output: {USA, India}
}
Output:
{USA, India}
6. Maps (Map)
The Map object is a key and value pair. Keys and values on a map may be of any type. It is a dynamic collection.
Declaring Map in Dart
While Declaring Map there can be only two cases one where declared Map is empty and another where declared Map contains elements in it. Both Cases are mentioned below:
1. Declaring Empty Map
// Method 1: Nullable Map declaration (can be assigned later)
Map? mapName;
// Method 2: Explicitly specifying key-value data types
Map<String, int>? mapName2;
// Method 3: Using the 'var' keyword with Map constructor
// Defaults to Map<dynamic, dynamic>
var mapName3 = Map();
// Method 4: Using a type-safe empty map
// Recommended approach
Map<String, int> mapName4 = {};
2. Declaring Map with Elements inside it.
/// Method 1: Using curly braces (preferred way)
Map<String, String> myMap = {
"First": "Geeks",
"Second": "For",
"Third": "Geeks",
};
// Method 2: Using Map constructor
Map<String, int> mapExample = Map();
mapExample["One"] = 1;
mapExample["Two"] = 2;
// Method 3: Using 'var' with implicit typing
var anotherMap = {
"A": 10,
"B": 20,
"C": 30,
};
Below is the implementation of Map in Dart:
Dart
void main() {
// Creating a map using the preferred syntax
Map<String, String> gfg = {};
// Adding key-value pairs
gfg['First'] = 'Geeks';
gfg['Second'] = 'For';
gfg['Third'] = 'Geeks';
// Printing the map
print(gfg);
}
Output:
{First: Geeks, Second: For, Third: Geeks}
7. Runes (Runes
)
Dart utilizes Runes to represent Unicode characters that fall outside the standard ASCII character set. Since Dart strings are encoded in UTF-16, certain special characters such as emojis and non-English scripts must be expressed using runes.
Declaring Runes in Dart
String heart = '\u2665'; // Unicode for ♥
Below is the implementation of Runes in Dart:
Dart
void main() {
// Unicode for heart symbol (♥)
String heart = '\u2665';
// Unicode for smiley face (☺)
String smiley = '\u263A';
// Unicode for star symbol (★)
String star = '\u2605';
// Unicode for musical note (♫)
String musicNote = '\u266B';
// Printing all Unicode symbols
print(heart); // Output: ♥
print(smiley); // Output: ☺
print(star); // Output: ★
print(musicNote); // Output: ♫
}
Output:
♥
☺
★
♫
8. Symbols (Symbol
)
A Symbol in Dart is an immutable identifier that represents variable names, method names, or metadata at runtime. Symbols are primarily used in reflection and are helpful for dynamic programming.
Declaring Symbols in Dart
Symbol sym1 = #mySymbol;
Symbol sym2 = Symbol("anotherSymbol");
Below is the implementation of Symbols in Dart:
Dart
void main() {
// Declaring a Symbol
// using the # syntax
Symbol sym1 = #dart;
// Declaring another Symbol
// with a different identifier
Symbol sym2 = #flutter;
// Printing the Symbols
print(sym1); // Output: Symbol("dart")
print(sym2); // Output: Symbol("flutter")
// Using Symbol in a map
// (useful for metadata or reflection)
Map<Symbol, String> symbolMap = {
#language: "Dart",
#framework: "Flutter",
};
// Printing values using Symbols as keys
print(symbolMap[#language]); // Output: Dart
print(symbolMap[#framework]); // Output: Flutter
}
Output:
Symbol("dart")
Symbol("flutter")
Dart
Flutter
9. Null (Null
)
Dart uses null to indicate the absence of a value. It has null safety, which means variables must be either nullable (?) or initialized before they can be used.
Declaring Null in Dart
String? name; // Can be null
Below is the implementation of Null in Dart:
Dart
void main() {
// Nullable variables (can be assigned null)
String? name;
int? age;
// Assigning values
name = "GFG";
age = null;
// Checking for null values
// using null-aware operators
print(name ?? "Unknown"); // Output: Vinay
print(age ?? "No age provided"); // Output: No age provided
// Using null-aware access (?.)
// and null assertion (!)
int? length = name?.length;
print(length);
// Output: 5
}
Output:
GFG
No age provided
3
Note: If the type of a variable is not specified, the variable’s type is dynamic. The dynamic keyword is used as a type annotation explicitly.
Similar Reads
Dart Tutorial Dart is an open-source general-purpose programming language developed by Google. It supports application development on both the client and server side. However, it is widely used for the development of Android apps, iOS apps, IoT(Internet of Things), and web applications using the Flutter Framework
7 min read
Basics
Data Types
Dart - Data TypesLike other languages (C, C++, Java), whenever a variable is created, each variable has an associated data type. In Dart language, there are the types of values that can be represented and manipulated in a programming language. In this article, we will learn about Dart Programming Language Data Types
8 min read
Basics of Numbers in DartLike other languages, Dart Programming also supports numerical values as Number objects. The number in Dart Programming is the data type that is used to hold the numeric value. Dart numbers can be classified as: int (Integer) The int data type is used to represent whole numbers.Declaring Integer in
6 min read
Strings in DartA Dart string is a sequence of UTF-16 code units. With the same rule as that of Python, you can use either single or double quotes to create a string. The string starts with the datatype String or Var : String string = "I love GeeksforGeeks";var string1 = 'GeeksforGeeks is a great platform for upgra
6 min read
Dart - SetsSets in Dart is a special case in List, where all the inputs are unique i.e. it doesn't contain any repeated input. It can also be interpreted as an unordered array with unique inputs. The set comes into play when we want to store unique values in a single variable without considering the order of t
6 min read
Dart Programming - MapIn Dart programming, Maps are dictionary-like data types that exist in key-value form (known as lock-key). There is no restriction on the type of data that goes in a map data type. Maps are very flexible and can mutate their size based on the requirements. However, it is important to note that all l
7 min read
Queues in DartDart also provides the user to manipulate a collection of data in the form of a queue. A queue is a FIFO (First In First Out) data structure where the element that is added first will be deleted first. It takes the data from one end and removes it from the other end. Queues are useful when you want
3 min read
Data Enumeration in DartEnumerated types (also known as enumerations or enums) are primarily used to define named constant values. The enum keyword is used to define an enumeration type in Dart. The use case of enumeration is to store finite data members under the same type definition. Declaring enumsenum variable_name{ //
3 min read
Control Flow
Key Functions
Dart - Anonymous FunctionsAn anonymous function in Dart is like a named function but they do not have names associated with it. An anonymous function can have zero or more parameters with optional type annotations. An anonymous function consists of self-contained blocks of code and that can be passed around in our code as a
2 min read
Dart - main() FunctionThe main() function is a predefined method in Dart. It is the most important and mandatory part of any dart program. Any dart script requires the main() method for its execution. This method acts as the entry point for any Dart application. It is responsible for executing all library functions, user
2 min read
Dart - Common Collection MethodsList, Set, and Map share common functionalities found in many collections. Some of this common functionality is defined by the Iterable class, which is implemented by both List and Set.1. isEmpty() or isNotEmptyUse isEmpty or isNotEmpty to check whether a list, set, or map has items or not.Example:D
2 min read
How to Exit a Dart Application Unconditionally?The exit() method exits the current program by terminating the running Dart VM. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination. This is a similar exit in C/C++, Java. This method doesn't wait for any asynchronous operations to term
2 min read
Dart - Getters and SettersGetters and Setters, also called accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively. Getters or accessors are defined using the get keyword.Setters or mutators are defined using the set keyword.A default getter/setter is associated with every
3 min read
Dart - Classes And ObjectsDart is an object-oriented programming language, so it supports the concept of class, object, etc. In Dart, we can define classes and objects of our own. We use the class keyword to do so. Dart supports object-oriented programming features like classes and interfaces.Let us learn about Dart Classes
4 min read
Object-Oriented Programming
Dart - this keywordthis keyword represents an implicit object pointing to the current class object. It refers to the current instance of the class in a method or constructor. The this keyword is mainly used to eliminate the ambiguity between class attributes and parameters with the same name. When the class attributes
2 min read
Dart - Static KeywordThe static keyword is used for the memory management of global data members. The static keyword can be applied to the fields and methods of a class. The static variables and methods are part of the class instead of a specific instance. The static keyword is used for a class-level variable and method
3 min read
Dart - Super and This keywordSuper Keyword in DartIn Dart, the super keyword is used to refer immediate parent class object. It is used to call properties and methods of the superclass. It does not call the method, whereas when we create an instance of subclass than that of the parent class is created implicitly so super keywor
4 min read
Dart - Concept of InheritanceIn Dart, one class can inherit another class, i.e. dart can create a new class from an existing class. We make use of extend keyword to do so.Terminology: Parent Class: It is the class whose properties are inherited by the child class. It is also known as a base class or super class.Child Class: It
5 min read
Instance and class methods in DartDart provides us with the ability to create methods of our own. The methods are created to perform certain actions in class. Methods help us to remove the complexity of the program. It must be noted that methods may or may not return any value, and also, they may or may not take any parameter as inp
3 min read
Method Overriding in DartMethod overriding occurs in Dart when a child class tries to override the parent class's method. When a child class extends a parent class, it gets full access to the methods of the parent class and thus it overrides the methods of the parent class. It is achieved by re-defining the same method pres
3 min read
Getter and Setter Methods in DartGetter and Setter methods are class methods used to manipulate the data of class fields. Getter is used to read or get the data of the class field, whereas setter is used to set the data of the class field to some variable. The following diagram illustrates a Person class that includes: A private va
2 min read
Abstract Classes in DartAn abstract class in Dart is defined as a class that contains one or more abstract methods (methods without implementation). To declare an abstract class, we use the abstract keyword. It's important to note that a class declared as abstract may or may not include abstract methods. However, if a clas
4 min read
Dart - Builder ClassIn Flutter, each widget has an associated build method responsible for rendering the UI. The Flutter framework automatically provides a BuildContext parameter to the build method.Widget build ( BuildContext context )Flutter takes care that there need not be any Widget apart from the build that needs
4 min read
Concept of Callable Classes in DartDart allows the user to create a callable class which allows the instance of the class to be called as a function. To allow an instance of your Dart class to be called like a function, implement the call() method. Syntax :class class_name { ... // class content return_type call ( parameters ) { ...
4 min read
Interface in DartThe interface in the dart provides the user with the blueprint of the class, which any class should follow if it interfaces that class, i.e., if a class inherits another, it should redefine each function present inside an interfaced class in its way. They are nothing but a set of methods defined for
3 min read
Dart - extends Vs with Vs implementsAll developers working with Dart for application development using the Flutter framework regularly encounter different usages of the implements, extends, and keywords. In Dart, one class can inherit another class, i.e. , Dart can create a new class from an existing class. We make use of keywords to
4 min read
Dart - Date and TimeA DateTime object is a point in time. The time zone is either UTC or the local time zone. Accurate date-time handling is required in almost every data context. Dart has the marvelous built-in classes for date time and duration in dart:core. Key Uses of DateTime in Dart:Comparing and Calculating Date
3 min read
Using await async in DartThe async and await approaches in Dart are very similar to other languages, which makes it a comfortable topic to grasp for those who have used this pattern before. However, even if you donât have experience with asynchronous programming using async/await, you should find it easy to follow along her
4 min read
Dart Utilities
Dart Programs
Dart - Sort a ListThe List data type is similar to arrays in other programming languages. A list is used to represent a collection of objects. It is an ordered group of objects. The core libraries in Dart are responsible for the existence of the List class, its creation, and manipulation. Sorting of the list depends
2 min read
Dart - String toUpperCase() Function with ExamplesThe string toUpperCase() method converts all characters of the string into an uppercase letter. The string toUpperCase() function returns the string after converting all characters of the string into the uppercase letter. Syntax: Str.toUpperCase()Parameter: The string toUpperCase() function doesn't
1 min read
Dart - Convert All Characters of a String in LowercaseWith the help of the toLowerCase() method in the string will convert all the characters in a string in lowercase.Syntax: String.toLowerCase() Return: string Image Representation: Example 1: Dart// main function start void main() { // initialise a string String st = "GEEKSFORGEEKS"; // print the stri
1 min read
How to Replace a Substring of a String in Dart?To replace all the substrings of a string, we make use of the replaceAll method in Dart. This method replaces all the substrings in the given string with the desired substring. Returns a new string in which the non-overlapping substrings matching from (the ones iterated by from.allMatches(this Strin
2 min read
How to Check String is Empty or Not in Dart (Null Safety)?We can check a string is empty or not by the String Property isEmpty. If the string is empty then it returns True if the string is not empty then it returns False.Syntax: String.isEmpty Return : True or False.Image Representation: Example 1:Dart// main function start void main() { // initialise a st
1 min read
Exception Handling in DartAn exception is an error that occurs inside the program. When an exception occurs inside a program, the normal flow of the program is disrupted, and it terminates abnormally, displaying the error and exception stack as output. So, an exception must be taken care of to prevent the application from te
3 min read
Assert Statements in DartAs a programmer, it is very necessary to make an errorless code is very necessary and to find the error is very difficult in a big program. Dart provides the programmer with assert statements to check for the error. The assert statement is a useful tool to debug the code, and it uses a Boolean condi
3 min read
Fallthrough Condition in DartFall through is a type of error that occurs in various programming languages like C, C++, Java, Dart ...etc. It occurs in switch-case statements where when we forget to add break statement and in that case flow of control jumps to the next line. "If no break appears, the flow of control will fall th
3 min read
Concept of Isolates in DartDart was traditionally designed to create single-page applications. We also know that most computers, even mobile platforms, have multi-core CPUs. To take advantage of all those cores, developers traditionally use shared-memory threads running concurrently. However, shared-state concurrency is error
2 min read
Advance Concepts