Data Types in Dart

Last Updated On Sunday 19th Dec 2021

Dart Data Types

In Dart, a type is a way to tell the compiler how you plan to use some data.int,double,num,dynamic,String

It’s good to always add the type annotation when you declare a variable.

	int myInt = 11;
double myDoub = 4.47;
	

By Declaring the variables like above makes them mutable. If you want to make them immutable, but still keep the type annotation, you can add const or final.

	const int myInt = 11;
const double myDoub = 4.47;
	

or

	final int myInt = 11;
final double myDoub = 4.47;
	
  • Mutable data is convenient to work – You can change it any time you want.
  • When a value is immutable – No one will change that value after you create it.

The is keyword

Checking the type at runtime.Dart
does have a programmatic way.

	void main() {
  double myNum = 3.14;
  print(myNum is int);
  print(myNum is double);
}
	
	void main() {
  num myNum = 3.14;
  print(myNum is int);
  print(myNum is double);
}
	
	false
true
	
  • Both double and int are subtypes of num. That means myNum could store either type.
  • use the runtimeType property that is available to all types.
	void main() {
  double myNum = 3.14;
  print(myNum.runtimeType);
}
	

It prints double as expected.

	double
	

A value of type ‘double’ can’t be assigned to a variable of type ‘int’.

	void main() {
  var integer = 20;
  var decimal = 2.5;
  integer = decimal;
}
	

Dart disallows you from assigning a value of one type to another.You can convert this double to an int.

	void main() {
  var integer = 20;
  var decimal = 2.5;
  integer = decimal.toInt();
}
	
  • int, double, num – Numbers in Dart are used to represent numeric literals.
  • string – Strings represent a sequence of characters
  • bool – It represents Boolean values true and false
  • list – It is an ordered group of objects
  • map – It represents a set of values as key-value pairs