0

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.

1 Answer 1

0

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;
1
  • I googled _network_image_io.dart, I found the constructor of NetworkImage that you said. And it's not an abstract class. Thank you so much for your help!
    – Pearl Lee
    Dec 8, 2022 at 6:17

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.