Dart – Filter items in a list by type

In Dart, it is easy to create a list or a collection to store objects of different types. This means a list could contain numbers, strings, boolean values, or any object. Here is an example:

var data = ['abc', 123, 456, 'def', false, {1, 2, 3}];


We will see how to filter items in above list by data types:

Example 1: Primitive types

testPrimitiveTypes() {
  var data = ['abc', 123, 456, 'def', 
              false, {1, 2, 3}, true, 123.456];

  final nums = data.whereType<num>();
  print('Numbers: $nums');

  final ints = data.whereType<int>();
  print('Integers: $ints');

  final strings = data.whereType<String>();
  print('Strings: $strings');

  final booleans = data.whereType<bool>();
  print('Booleans: $booleans');
}


Example 2: Custom object type

void testCustomObjectType() {
  final people = [
    Student('Student 1', 'School 1'),
    Worker('Worker 1', 'Company 1'),
    Student('Student 2', 'School 1'),
    Worker('Worker 2', 'Company 2'),
    Student('Student 3', 'School 3'),
    Worker('Worker 3', 'Company 3'),
  ];

  final students = people.whereType<Student>();
  print(students);
  print('\n');
  final workers = people.whereType<Worker>();
  print(workers);
}

class Person {
  final String name;

  Person(this.name);
}

class Student extends Person {
  final String school;

  Student(String name, this.school) : super(name);

  @override
  String toString() {
    return 'Student: { name: $name, school: $school}';
  }
}

class Worker extends Person {
  final String company;

  Worker(String name, this.company) : super(name);

  @override
  String toString() {
    return 'Worker: { name: $name, company: $company}';
  }
}


Main method

main() {
  testPrimitiveTypes();
  print('------------');
  testCustomObjectType();
}


Output

Numbers: (123, 456, 123.456)
Integers: (123, 456)
Strings: (abc, def)
Booleans: (false, true)
------------
(Student: { name: Student 1, school: School 1}, 
 Student: { name: Student 2, school: School 1}, 
 Student: { name: Student 3, school: School 3})

(Worker: { name: Worker 1, company: Company 1}, 
 Worker: { name: Worker 2, company: Company 2}, 
 Worker: { name: Worker 3, company: Company 3})

Tagged : / / / /
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x