Evaluate a variable’s data type in Dart

is and is! operators can be used to determine a variable’s data type or class.


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');

Leave a Comment

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.