Difference in NetworkImage and Image.network?

2020-03-01 06:20发布

问题:

Are there any difference in both of them?

Whats the disadvantage and which one is easier to use for normal situation?

回答1:

Are there any difference in both of them?

Yes. They are different.

  • NetworkImage class creates an object the provides an image from the src URL passed to it. It is not a widget and does not output an image to the screen.
  • Image.network creates a widget that displays an image on the screen. It is just a named constructor on the Image class(a stateful widget). It sets the image property using the NetworkImage . This image property is used finally to display the image.

    class Image extends StatefulWidget{
      Image(...){}; //default Constructor
    
    
      //the argument src is passed to the NetworkImage and assinged to the image property
      Image.network(String src, {...}) : image = NetworkImage(src, ...);
    
    
      final ImageProvider image;
    
      @override
      Widget build(BuildContext context){
        display the image
        return RawImage(image: image,
          ...
        );
      }
    }
    

Whats the disadvantage and which one is easier to use for normal situation?

There is no disadvantage. You should use the one the suits the need. For example consider:

  1. CircleAvatar widget that displays acircle that represents a user takes backgroundImage. It requires an ImageProvider. So you pass NetworkImage(http://image.com)
  2. FadeInImage that displays a placeholder while the original image is loading also takes a ImageProvider for its image property. So you can provide it NetworkImage(http://image.com).

If you just want to display the image as a widget on screen use Image.network and use NetworkImage wherever an ImageProvider is expected.



标签: dart flutter