Is there a way to inquire if a class contains an instance variable with some known name?

Issue

When intercepting an error from MySql, it’s not known beforehand what will be the contents of the error-class passed to me. So I code:

.catchError((firstError) {
  sqlMessage = firstError.message; 
  try {        
    sqlError = firstError.osError;
  } catch (noInstanceError){
    sqlError = firstError.sqlState;
  }
});

In this specific case I’d like to know whether e contains instance variable osError or sqlState, as any of them contains the specific errorcode. And more in general (to improve my knowledge) would it be possible write something like if (firstError.instanceExists(osError)) ..., and how?

Solution

This should do what you want:

import 'dart:mirrors';

...

// info about the class declaration
reflect(firstError).type.declarations.containsKey(#osError);

// info about the current instance
var m = reflect(firstError).type.instanceMembers[#osError];
var hasOsError = m != null && m.isGetter;

Answered By – Günter Zöchbauer

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.