Build Status Coverage Status PRs Welcome pub package


Disk lru cache for flutter. wiki

A cache that uses a bounded amount of space on a filesystem. Each cache entry has a string key and a fixed number of files, witch is accessible as stream.

Use cases

Working with memery

We provided a LruMap ,in order to support LRU order in memory, witch is a subclass of Map.So ,wo can use the LruMap just like Map

final LruMap<String, int> map = new LruMap();

expect(map.values.toList().length, 0);

map['a'] = 1;
map['b'] = 2;
map['c'] = 3;

/// use the key 'a'
var f = map['a'];

/// We use the key 'a', so at this moment it is the last element.
alues = map.values;
expect(values.toList()[0], 2);
expect(values.toList()[1], 3);
expect(values.toList()[2], 1);

Working with file system

The basic usage is like this:

With string:

int maxSize =
      10 * 1024 * 1024; // 10M

// Make sure it's writable
Directory cacheDirectory =
            new Directory("${Directory.systemTemp.path}/cache");

 DiskLruCache cache = new DiskLruCache(
        maxSize: maxSize, directory: cacheDirectory, filesCount: 1);

    // write stream
    CacheEditor editor = await cache.edit('filekey');
      IOSink sink = await editor.newSink(0);
      sink.write('your value');
      await sink.close();
      await editor.commit();

    // read stream
    CacheSnapshot snapshot =  await cache.get('filekey');
    String str = await snapshot.getString(0);

With bytes

// write bytes
  CacheEditor editor = await cache.edit('imagekey');
    HttpClient client = new HttpClient();
    HttpClientRequest request = await client.openUrl("GET", Uri.parse(""));
    HttpClientResponse response = await request.close();
    Stream<List<int>> stream = await editor.copyStream(0, response);
    // The bytes has been written to disk at this point.
    await new ByteStream(stream).toBytes();
    await editor.commit();

    // read stream
    CacheSnapshot snapshot =  await cache.get('imagekey');
    Uint8List bytes = await snapshot.getBytes(0);

Manage the cache

Get the bytes of the cache in file system

DiskLruCache cache = ...;

Clean the cache

DiskLruCache cache = ...;