Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extension of abstract class doesn't work properly in Dart

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

The Code

I have following files:

BaseListItem.dart

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading