Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between an "Image" and "ImageProvider" in Flutter?

There are answers related to this topic but they offer workarounds rather than explanations.

Why can't an Image be used where an ImageProvider is required? Conceptually they sound the same to me.

child: new CircleAvatar(
  backgroundImage: NetworkImage("https..."),        // works
  backgroundImage: Image.asset('images/image.png'), // error
),

The error generated by trying to use an image directly is:

error: The argument type 'Image' can't be assigned to the parameter type 'ImageProvider'.

like image 502
Pete Alvin Avatar asked Nov 27 '19 18:11

Pete Alvin


3 Answers

Image vs ImageProvider

An image provider is what provides the image to an Image widget. ;D

The image provider doesn't necessarily have the image right there but it knows how to get it.

Getting an Image

If you need an Image widget, then use one of these:

  • Image.asset()
  • Image.network()
  • Image.file()
  • Image.memory()

Getting an ImageProvider

If you need an ImageProvider, then use one of these:

  • AssetImage()
  • NetworkImage()
  • FileImage()
  • MemoryImage()

Converting an ImageProvider to an Image

If you have an ImageProvider object and you want an Image widget, then do the following:

Image(
  image: myImageProvider,
)

Converting an Image to an ImageProvider

If you have an Image widget and you need its ImageProvider, then do the following:

myImageWidget.image
like image 95
Suragch Avatar answered Sep 20 '22 11:09

Suragch


An Image is a widget that displays an image.

The ImageProvider instead allows you to identify an image without knowing exactly where is the final asset. The place of the asset will be resolved later when someone wants to read the image.

like image 35
Ricardo Markiewicz Avatar answered Sep 18 '22 11:09

Ricardo Markiewicz


Actually Every background and Foreground Decoration will accept only ImageProvider like AssetImage(),NetworkImage(),FileImage(),MemoryImage()...

And when you try to build a widget then its take Image.asset(),Image.network(), Image.file(), Image.memory()...

like image 30
Vishal_VE Avatar answered Sep 20 '22 11:09

Vishal_VE