speify in a list that states that each element is a string or an integer?
How can I write a for loop in a list that states that each element is a string or an integer?
for example var score=[gold, 3, bronze, silver, 4]
for (int i = 0; i < score.length; i++) {
if (score[i] == int) {
print('int');
}}
or
for (int i = 0; i < score.length; i++) {
if (score[i] == String) {
print('String');
}}
is it possible in dart.
Solution 1:
I should first say that having lists containing multiple different types of data (where the common interface is Object
) is not a sound design, in most cases, and does show a bad data model.
What you are looking for is the is
-operator documented here in the Dart Language Tour: https://dart.dev/guides/language/language-tour#type-test-operators
With this, you can write the following code. I have also replaced your normal for-loop with a for-each loop since that is better if you don't need to i
variable and just want to iterate over the list.
void main() {
var score=['gold', 3, 'bronze', 'silver', 4];
for (final element in score) {
if (element is String) {
print('Scrore is the following String: $element');
} else if (score is int) {
print('Scrore is the following int: $element');
} else {
print('The score is not a String or int');
}
}
}