Shubham Patel
Shubham Patel

Reputation: 61

how to check if getter is defined or not for a class in dart?

Is there any way to check if a getter is provided for a dynamic variable in dart other then in try catch block?

example
here 'v1' is not provided in 'ThisClass' so it will give an error

class ThisClass{
  bool v2=false;
}

main() {
  dynamic h=ThisClass();
  
  print(h.v1);
}

Upvotes: 3

Views: 1035

Answers (2)

Doc
Doc

Reputation: 11651

You could do

class ThisClass {
  bool v2 = false;
}

main() {
  dynamic h = ThisClass();
  if (h is ThisClass) {
    print(h.v2);
  }
}

Upvotes: 4

adamgy
adamgy

Reputation: 5623

You can attempt to access the variable in a try block and catch the resulting error if it doesn't exist:

try {
  print(h.v1);
} catch (e) {
  // Handle the error
}

Upvotes: 1

Related Questions