Skip to main content

Type Checking

When creating a lint rule, you will often need to check if a node is of a certain type. For example, you may want to find all class declarations which extend StatelessWidget in order to perform some analysis on them.

Unfortunately, we cannot just use the is keyword to check if a node is of a certain type, because the analyzer can only provide us with DartType objects, which are not the same as the Type objects we'd typically use when checking types in Dart programs.

Fortunately, Sidecar ships with its own TypeChecker utility, which provides an easy way for checking if an AstNode is of a certain type:


// 1. Create the TypeChecker
const statelessWidget =
TypeChecker.fromPackage('StatelessWidget', package: 'flutter');


class MyLint extends LintRule {


void visitInstanceCreationExpression(InstanceCreationExpression node) {
// 2. Use the TypeChecker to check the type of a particular AstNode
final returnType = node.constructorName.staticElement?.returnType;
if (statelessWidget.isAssignableFromType(returnType)) {
// do something
}
}

}

There are two notable ways to create a TypeChecker:

  • TypeChecker.fromName - Used for non-Dart packages
  • TypeChecker.fromDartType - Used for dart packages like dart:core or dart:async


void visitInstanceCreationExpression(InstanceCreationExpression node) {
// 2. Use the TypeChecker to check the type of a particular AstNode
const colorTypeChecker = TypeChecker.fromDart('Color', package: 'ui');
final returnType = node.constructorName.staticElement?.returnType;
if (colorTypeChecker.isAssignableFromType(returnType)) {
// do something
}
}

In both cases, the utility takes the name of the Type and the name of the Type's package.