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

江枫思渺然 提交于 2021-01-22 04:20:32

问题


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'.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/59076399/what-is-the-difference-between-an-image-and-imageprovider-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!