Home > Blockchain >  Can I create an instance of Abstract class?
Can I create an instance of Abstract class?

Time:12-08

I have a question about NetworkImage of Flutter.

CircleAvatar(
  backgroundImage: NetworkImage(''),
),

backgroundImage of CircleAvatar accept ImageProvider type. But ImageProvider class is an abstract class, so other subtype like AssetImage, FileImage, NetworkImage class object can be assigned to backgroundImage. That code doesn't have any problem.

abstract class NetworkImage extends ImageProvider<NetworkImage> {
  const factory NetworkImage(String url, { double scale, Map<String, String>? headers }) = network_image.NetworkImage;

  String get url;
  double get scale;

  Map<String, String>? get headers;

  @override
  ImageStreamCompleter load(NetworkImage key, DecoderCallback decode);

  @override
  ImageStreamCompleter loadBuffer(NetworkImage key, DecoderBufferCallback decode);
}

Here is my question. NetworkImage class is also an abstract class. I have learned that abstract class can't be instantiated, but NetworkImage can be instantiated although it is an abstract class.

How can it be done?

ImageProvider() can't be assigned to the backgroundImage because it's an abstract class so it can't be instantiated.

CodePudding user response:

Abstract class can't be initiated.

But you may ask if NetworkImage is abstract why we can use it in the CircleAvatar by providing the URL like in the example below

NetworkImage('url/to/image.png')

The answer is you are not initiating exact NetworkImage from image_provider.dart because you are calling a factory constructor that under the hood returns network_image.NetworkImage which is the constructor of NetworkImage class from _network_image_io.dart

const factory NetworkImage(String url, { double scale, Map<String, String>? headers }) = network_image.NetworkImage;
  • Related