Home > Software design >  Extension of abstract class doesn't work properly in Dart
Extension of abstract class doesn't work properly in Dart

Time:08-26

I have faced with strange behavior of extensions of abstract class in the Dart.

The Code

I have following files:

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

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.

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);
        });
  }
}

The problem

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.❗️

CodePudding user response:

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?

  • Related