初始化所有具有相同 ID 的 Flutter class 个实例,无需提供参数
Initialize all Flutter class instances with same ID and no need to provide argument
我正在开发一个 flutter 应用程序,希望我的 class 中的一个拥有相同的 id
属性。这是因为我可以有一个事件或一个异常,但我想要同一个函数来管理这两者。为此,我有一个 switch 语句来检查 res.id
以确定它是哪种类型的事件。响应可以是 Event
实例或 Exception
实例。
Exception
是一个导入 class,我宁愿不必将它包装在 Event
实例中,所以我认为我可以硬编码 id = EventIds.error
。这样每个错误都会有一个与错误事件匹配的 id - 因此可以在原始 switch 语句中访问和处理它。
我的问题是我不想遍历所有代码并为每个实例化添加一个新参数。请参阅下面的代码。
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]);
}
实例化电流
Exception ex = new Exception(-93, 'Unable to validate')
我希望能够让 Exception
的每个实例都具有 EventIds.error
的 id,而无需 必须通过我的代码中的每个实例化,并且像这样添加:
Exception ex = new Exception(EventIds.error, -93, 'Unable to validate')
这在 Flutter 中可以实现吗?
真的很简单。我只需要像这样写出我的异常 class:
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]);
}
这样实例将始终使用 id
的默认值。这也更安全,因为现在用户如果想提供另一个参数 (Exception(supplied_id, code, message)
) 就不能更改 ID,因为它会抛出语法错误,指出第二个参数应该是一个字符串。
我正在开发一个 flutter 应用程序,希望我的 class 中的一个拥有相同的 id
属性。这是因为我可以有一个事件或一个异常,但我想要同一个函数来管理这两者。为此,我有一个 switch 语句来检查 res.id
以确定它是哪种类型的事件。响应可以是 Event
实例或 Exception
实例。
Exception
是一个导入 class,我宁愿不必将它包装在 Event
实例中,所以我认为我可以硬编码 id = EventIds.error
。这样每个错误都会有一个与错误事件匹配的 id - 因此可以在原始 switch 语句中访问和处理它。
我的问题是我不想遍历所有代码并为每个实例化添加一个新参数。请参阅下面的代码。
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]);
}
实例化电流
Exception ex = new Exception(-93, 'Unable to validate')
我希望能够让 Exception
的每个实例都具有 EventIds.error
的 id,而无需 必须通过我的代码中的每个实例化,并且像这样添加:
Exception ex = new Exception(EventIds.error, -93, 'Unable to validate')
这在 Flutter 中可以实现吗?
真的很简单。我只需要像这样写出我的异常 class:
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]);
}
这样实例将始终使用 id
的默认值。这也更安全,因为现在用户如果想提供另一个参数 (Exception(supplied_id, code, message)
) 就不能更改 ID,因为它会抛出语法错误,指出第二个参数应该是一个字符串。