26

I'm an Android developer trying to learn flutter. I'm stuck in checking whether an object is an instance of a class (A stateful or stateless widget) or not.

In Java we use like

if (object instanceOf MyClass) {
   // object is an instance of MyClass
} else {
   //  object is not an instance of MyClass
}

But i don't know how to do it in flutter.

So far I've tried,

if (object is MyClass) {
   // object is an instance of MyClass
} else {
   //  object is not an instance of MyClass
}

but this is always false.

I've seen another possible way of doing it new isInstanceOf<MyClass>() which is available in package:matcher/matcher.dart package but i don't know how to implement it properly.

Any help would be great. Thanks in advance.

Vinoth Kumar
  • 12,637
  • 5
  • 32
  • 38

4 Answers4

31

is works perfect with Widget classes. For example I have a widget

class AccountCreationPage extends StatefulWidget {...}

Then I can check that my variable of type Widget is of AccountCreationPage class (gives true, if it is really this class):

_loginPage is AccountCreationPage ? 'Creation' : ""
Valentina Konyukhova
  • 4,464
  • 2
  • 24
  • 33
12

Try using debugging your object's class:

debugprint("$<object name>");

And then manually match the class types.

That means that you will find out the needed class for the is operator.

object is <object's class>
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
akash
  • 587
  • 4
  • 16
  • This is not working for me. `debugprint("$_page")` prints `MainPage` and `if (_page is MainPage)` evaluates to false. – Vinoth Kumar May 30 '18 at 11:49
1

You can use equals operator

class MyApp extends StatelessWidget {
    @override
  bool operator ==(Object o) {
    if (identical(this, o)) return true;

    return o is MyApp;
  }
}

Then check as following

if (object == MyApp)
Sinan Aktepe
  • 142
  • 1
  • 2
0

According to Flutter Dart-js-util-library you can check as below:

if (instanceOf(object, MyClass)) {
   print ('instance of MyClass');
} else {
   print('unknown instance');
}

Note This is web only library, won't work on iOS or Android

vijay
  • 831
  • 9
  • 14