Learning how to evaluate a variable’s data type in Dart is an essential skill for any developer. Knowing how to evaluate a variable’s data type in Dart can help developers improve the performance and accuracy of their code. Furthermore, it can help to ensure that developers write code that is consistent and reliable. This article will explain how to evaluate a variable’s data type in Dart and provide examples of how to do so.
Dart is a statically-typed language, which means that variables must have a declared data type at the time of creation. However, Dart also supports type inference, which means that the data type of a variable can be inferred by the compiler based on the assigned value.
is
andis!
operators can be used to determine a variable’s data type or class.- You can use the
runtimeType
property. This property returns the runtime type of the object, which can be used to determine the data type of a variable.
Example
var data = ["Hello", 5, 5.12, [], {}, User('username', 'password')];
Using is
and is!
:
if (data[0] is String) print(data[0]);
if (data[1] is int) print(data[1]);
if (data[2] is! int) print(data[2]);
if (data[3] is List) print('List');
if (data[4] is Object) print('Object');
if (data[5] is User) print(data[5].toString());
Another approach is to use .runtimeType
to get the type.
if (data[1].runtimeType == int) print('Int');
if (data[3].runtimeType == [].runtimeType) print('List');
More examples
var num = 42;
var str = "Hello, world!";
var list = [1, 2, 3];
var map = {'key': 'value'};
print(num.runtimeType); // int
print(str.runtimeType); // String
print(list.runtimeType); // List<int>
print(map.runtimeType); // _InternalLinkedHashMap<String, String>
var num = 42;
var str = "Hello, world!";
if (num is int) {
print("num is an integer");
}
if (str is! int) {
print("str is not an integer");
}