使用缓存图片

在一些情况下,缓存从网络下载的图片用于离线显示是十分方便的。你需要引入 cached_network_image 包来实现这项功能。

In some cases, it’s handy to cache images as they’re downloaded from the web, so they can be used offline. For this purpose, use the cached_network_image package.

除了缓存,cached_image_network 包也支持占位符和加载后的图片淡入。

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

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

添加占位符

Adding a placeholder

cached_network_image 包允许任何 Widget 充当占位符。在本例中,加载图片时会展示一个旋转加载的效果(spinner)作为占位符。

The cached_network_image package allows you to use any widget as a placeholder. In this example, display a spinner while the image loads.

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

完整样例

Complete example

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final title = 'Cached Images';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: Center(
          child: CachedNetworkImage(
            placeholder: (context, url) => CircularProgressIndicator(),
            imageUrl:
                'https://picsum.photos/250?image=9',
          ),
        ),
      ),
    );
  }
}