Search code examples
dartoperators

Dart Operators : The name 'b' isn't a type and can't be used in an 'is' expression


I'm new to dart and reading about dart operators. In the book fluter in Action by Eric Windmill (Chapter 2, 2.24, page 34) the auther says:

is and is! verify that two objects are of the same type. They are equivalent to == and !=.

Trying to implement this as shown in the code below

void main() {
    int a = 7;
    int b = 2;
    bool z = a == b; // It works when I use the equals symbol
    print('Result: $z');
}

But when I use the ```is`` keyword, I get an error

void main() {
    int a = 7;
    int b = 2;
    bool z = a is b; // It doesn't work here
    print('Result: $z');
}

Error

The name 'b' isn't a type and can't be used in an 'is' expression.
Try correcting the name to match an existing type.

Solution

  • Not sure what the context of that statement is but is and is! is not the same as == and != in the sense that they does the same. I guess what the want to explain, is that the opposite of is is is! like the opposite of == is !=.

    == is used to check if two objects are equal (based on what this object at left side defines to be equal). So for int we return true when using == if both numbers have the same numeric value.

    The is operator is used to test if a given object does implement a given interface. An example:

    void main() {
      Object myList = <int>[];
      
      if (myList is List<int>) {
        print('We have a list of numbers.');
      }
    }
    

    The error you are getting are telling you that for using is you need to provide an actual type at the right side of the is and not an object instance.