[英]Extension of abstract class doesn't work properly in Dart
I have faced with strange behavior of extensions of abstract class in the Dart.我在 Dart 中遇到了抽象 class 扩展的奇怪行为。
I have following files:我有以下文件:
BaseListItem.dart BaseListItem.dart
abstract class BaseListItem {
ImageProvider get _icon;
IHealthChecker get _healthChecker;
String get _name;
String get _unit;
Widget build(BuildContext context) {
... build widgets tree ...
}
}
Temperature.dart温度.dart
class Temperature extends BaseListItem {
@override
IHealthChecker get _healthChecker => TemperatureHealthChecker();
@override
ImageProvider<Object> get _icon => const Svg('assets/images/icons/Temperature.svg');
@override
String get _name => "Temperature";
@override
String get _unit => "°C";
}
And all this inheritance stuff I am using in SensorsList.dart file.我在SensorsList.dart文件中使用的所有这些 inheritance 东西。
class SensorsList extends StatefulWidget {
@override
State<StatefulWidget> createState() => _StateSensorsList();
}
class _StateSensorsList extends State<SensorsList> {
final List<BaseListItem> sensors = [Temperature(), Humidity()];
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: sensors.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return sensors[index].build(context);
});
}
}
This code built but fail at run time with next exception此代码已构建但在运行时失败并出现下一个异常
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: Class 'Temperature' has no instance getter '_icon'.
Receiver: Instance of 'Temperature'
Tried calling: _icon)
❗️The problem disappears if I put abstract class BaseListItem and his extension Temperature into a single file.❗️ ❗️如果我将抽象 class BaseListItem 和他的扩展温度放在一个文件中,问题就消失了。❗️
The reason why it happens is because the variables are private.它发生的原因是因为变量是私有的。 Private variables can only be accessed within the same file.私有变量只能在同一个文件中访问。 See also In Dart, how to access a parent private var from a subclass in another file?另请参阅在 Dart 中,如何从另一个文件中的子类访问父私有 var?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.