I am working on a flutter app and wanted one of my classes to have the same id
property. This is because I can have either an event or an exception, but I would like the same function to manage both. To do this, I have a switch statement that checks res.id
to determine which type of event it is. The response can either be an Event
instance or an Exception
instance.
Exception
is an import class and I'd rather not have to wrap it in an Event
instance so I thought I could just hardcode id = EventIds.error
. This way every error will have an id that matches an error event - thus it can be accessed and dealt with in the original switch statement.
My issue is I don't want to have to go all throughout my code and add a new argument to each instantiation. See the code below.
Exception.dart
class Exception {
/// Always initialize with id that is error id
/// This is for onCaptureEvent
int id = EventIds.error;
int code = 0;
String message = 'no error';
String? method;
String? details;
Exception(id, this.code, this.message, [this.method, this.details]);
}
Instantiation Current
Exception ex = new Exception(-93, 'Unable to validate')
I want to be able to have every instance of Exception
have an id of EventIds.error
WITHOUT having to go through every instantiation in my code and add it like so:
Exception ex = new Exception(EventIds.error, -93, 'Unable to validate')
Is this achievable in Flutter?
CodePudding user response:
It was really simple. I just needed to write out my Exception class like so:
Exception.dart
class Exception {
/// Always initialize with id that is error id
/// This is for onCaptureEvent
int id = EventIds.error;
int code = 0;
String message = 'no error';
String? method;
String? details;
Exception(this.code, this.message, [this.method, this.details]);
}
This way the instances will always use the default value for id
. This is also safer bc now the user cannot change the ID if they wanted to provide another argument (Exception(supplied_id, code, message)
) because it will throw a syntax error saying the second argument is supposed to be a string.