In some cases, it can be handy to cache images as they’re downloaded from theweb so they can be used offline. For this purpose, you’ll employ thecached_network_image package.

In addition to caching, the cached_image_network package also supportsplaceholders and fading images in as they’re loaded.

  1. CachedNetworkImage(
  2. imageUrl: 'https://picsum.photos/250?image=9',
  3. );

Adding a placeholder

The cached_network_image package allows you to use any Widget as aplaceholder. In this example, you’ll display a spinner while the image loads.

  1. CachedNetworkImage(
  2. placeholder: (context, url) => CircularProgressIndicator(),
  3. imageUrl: 'https://picsum.photos/250?image=9',
  4. );

Complete example

  1. import 'package:flutter/material.dart';
  2. import 'package:cached_network_image/cached_network_image.dart';
  3. void main() {
  4. runApp(MyApp());
  5. }
  6. class MyApp extends StatelessWidget {
  7. @override
  8. Widget build(BuildContext context) {
  9. final title = 'Cached Images';
  10. return MaterialApp(
  11. title: title,
  12. home: Scaffold(
  13. appBar: AppBar(
  14. title: Text(title),
  15. ),
  16. body: Center(
  17. child: CachedNetworkImage(
  18. placeholder: (context, url) => CircularProgressIndicator(),
  19. imageUrl:
  20. 'https://picsum.photos/250?image=9',
  21. ),
  22. ),
  23. ),
  24. );
  25. }
  26. }