What is "as" in Dart language?

Mon, Dec 5, 2022

Read in 2 minutes

In this post we will take a look at "as" keyword in Dart with some example codes.

In Dart, the as keyword is used to perform type casting. Type casting is the process of converting a value of one data type to another data type. The as keyword is used to explicitly cast a value to a specified type.

Here’s an example of using the as keyword to cast an object to a specific type:

class Person {
  String name;
  int age;

  Person(this.name, this.age);
}

class Student extends Person {
  String school;

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

void main() {
  Person person = Student('Alice', 20, 'XYZ University');

  // Cast person to a Student object using the 'as' keyword
  Student student = person as Student;

  print(student.name);    // Output: Alice
  print(student.school);  // Output: XYZ University
}

In this example, we have a Person class and a Student class that extends Person. We create a Student object and assign it to a Person variable. We then use the as keyword to cast the Person object to a Student object.

If the value cannot be cast to the specified type, a TypeError is thrown at runtime. Here’s an example:

void main() {
  Person person = Person('Alice', 20);

  // Cast person to a Student object using the 'as' keyword
  Student student = person as Student;  // Throws a TypeError
}

In this example, we attempt to cast a Person object to a Student object using the as keyword. Since person is not an instance of Student, a TypeError is thrown at runtime.

The as keyword can also be used with nullable types. When casting a nullable type using the as keyword, if the value is null, the result is also null. Here’s an example:

void main() {
  Person? person = null;

  // Cast person to a Student object using the 'as' keyword
  Student? student = person as Student?;

  print(student);  // Output: null
}

In this example, we declare a nullable Person variable and assign it a value of null. We then attempt to cast it to a Student object using the as keyword. Since the value is null, the result is also null.


Shohruh AK





See Also

What is "abstract" in Dart language?
Everything you need to know about Dart language
What is Dart programming language in a nutshell?
Begginer's guide to using List in Dart/Flutter