In Flutter/Dart, what is the difference between using "==" vs "is" in a conditional if statement

Viewed 671

I am doing a tutorial on BLoC in Flutter and the tutor uses the keyword "is" in his conditional if statement, which he said "smartcasts" the state. Can anyone help me understand how the "is" operator gives me access to the bloc's state in the code below?

BlocBuilder<WeatherBloc, WeatherState>(
            builder: (context, state) {
              if (state is WeatherLoaded) {
                return buildColumnWithData(context,state.weather);
              }

When I tried the same code with if (state == WeatherLoaded), I'm not able to pass the state.weather into the buildColumnWithData function. Why is this?

1 Answers

'==' is an equality operator.

To test whether two objects x and y represent the same thing, use the == operator. (In the rare case where you need to know whether two objects are the exact same object, use the identical() function instead.) Here’s how the == operator works:

If x or y is null, return true if both are null, and false if only one is null.

Return the result of the method invocation x.==(y). (That’s right, operators such as == are methods that are invoked on their first operand. For details, see Operators.)

'is' is a type test operator

The result of obj is T is true if obj implements the interface specified by T. For example, obj is Object is always true.

In your code:

is checks if state is instance of WeatherLoaded class.

On top of that, you don't need to make a cast to WeatherLoaded if the check was successful - in the scope of the if statement state variable is downcast to WeatherLoaded ("is smartcasts the state").

With == operator, you can compare 2 instances of a class.

Related