Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"is" operator expected behavior in dart flutter

I have slightly strange issue (I am probably missing something)
I decided to iterate over element tree in Flutter and had the following question:

if (element.widget.runtimeType == GestureDetector) {
        print('return true1');
}
if (element.widget.runtimeType is GestureDetector) {
        print('return true2');
}

The runtype of my widget seems to be GestureDetector (that what I see in the debugger).
When I compare with == I see the return true1 as expected.
BUT why when I compare it with is operator I don’t see the return true2
That’s kinda strange,
why the is operator doesn’t return true2?
according to docs:
The result of obj is T is true if obj implements the interface specified by T
link

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

runtimeType is a property available to every object in dart. It has type of ‘Type’.

So when you do

if (element.widget.runtimeType == GestureDetector) {
        print('return true1');
}

it is checking if runtimeType is GestureDetector where the value of runtimeType is GestureDetector but type is Type.

When you are doing,

if (element.widget.runtimeType is GestureDetector) {
        print('return true2');
}

It is checking of type of runtimeType is GestureDetector, which is not true as it is Type.

To check if widget is GestureDetector, you should be doing

if (element.widget is GestureDetector) {
        print('return true2');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading