快速缓存网络图片

一个Flutter包,可快速缓存网络图片,无需原生依赖,并带有加载器、错误构建器和流畅的淡入过渡效果。

MIT License pub dart

截图

App caching

Caching with fade in animation

下面的GIF显示了缓存中的30MB图片。使用shimmer包创建一个漂亮的加载小部件。 加载大型缓存图片文件

用法

依赖它

import 'package:fast_cached_network_image/fast_cached_network_image.dart';

使用path_provider为图片数据库设置存储位置。

String storageLocation = (await getApplicationDocumentsDirectory()).path;

初始化缓存配置

await FastCachedImageConfig.init(path: storageLocation, clearCacheAfter: const Duration(days: 15));

clearCacheAfter属性用于设置缓存图片将被清除的持续时间。默认设置为7天,这意味着今天缓存的图片将在7天后打开应用时删除。

将其用作Widget

child: FastCachedImage(url: url)

属性

errorBuilder: (context, exception, stacktrace) {
          return Text(exception.toString());
        },

errorBuilder属性需要返回一个小部件。如果加载提供的图片时出现任何错误,将显示此小部件。

loadingBuilder: (context) {
          return Container(color: Colors.red, height: 100, width: 100);
        },

loadingBuilder属性可用于显示加载小部件,例如闪烁效果。在图片下载和处理过程中将显示此小部件。

fadeInDuration: const Duration(seconds: 1)

fadeInDuration属性可用于设置loadingBuilder和图片之间的淡入持续时间。默认持续时间为500毫秒。

如果图片在显示时出现错误,当再次请求图片时,图片将自动重新下载。

FastCachedImage具有Flutter提供的所有其他默认属性,如高度、宽度等。

示例

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  String storageLocation = 'E:/fast';
  await FastCachedImageConfig.init(path: storageLocation, clearCacheAfter: const Duration(days: 15));

  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String url1 = 'https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg';


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: SizedBox(
      height: 350,
      width: 350,
      child: FastCachedImage(
        url: url1,
        fit: BoxFit.cover,
        fadeInDuration: const Duration(seconds: 1),
        errorBuilder: (context, exception, stacktrace) {
          return Text(exception.toString());
        },
        loadingBuilder: (context) {
          return Container(color: Colors.grey);
        },
      ),
    )));
  }
}

pub.dev上的包

fast_cached_network_image

GitHub

查看 Github