disk_lru_cache 0.0.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 65

Build Status Coverage Status PRs Welcome pub package

disk_lru_cache #

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("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1534075481&di=1a90bd266d62bc5edfe1ce84ac38330e&src=http://photocdn.sohu.com/20130517/Img376200804.jpg"));
    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 = ...;

[0.0.2] #

  • Use synchronized library.

[0.0.1] - Basic usage. #

  • LRU Map
  • Store One CacheEntry with multiple files by using CacheEditor
  • Get CacheSnapshot and open streams directly from CacheEntry
  • Using a key to remove from cache
  • A record file to store all operation info,including 'DIRTY','CLEAN','REMOVE','READ'
  • Get total size from cache
  • When cache.size > caches.maxSize , auto trim to size.


import 'package:flutter/material.dart';

import 'test_disk_cache.dart';

void main() async {
  await testCache();

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        // This is the theme of your application.
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in IntelliJ). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: Colors.blue,
      home: new MyHomePage(title: 'Flutter Demo Home Page'),

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  _MyHomePageState createState() => new _MyHomePageState();

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.

  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return new Scaffold(
      appBar: new AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: new Text(widget.title),
      body: new Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: new Column(
          // Column is also layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          // Invoke "debug paint" (press "p" in the console where you ran
          // "flutter run", or select "Toggle Debug Paint" from the Flutter tool
          // window in IntelliJ) to see the wireframe for each widget.
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            new Text(
              style: Theme.of(context).textTheme.display1,
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  disk_lru_cache: ^0.0.2

2. Install it

You can install packages from the command line:

with Flutter:

$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:disk_lru_cache/disk_lru_cache.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on Jul 2, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.9+1
  • Flutter: 1.17.3

Analysis suggestions

Package not compatible with SDK dart

because of import path [disk_lru_cache]

Package not compatible with runtime flutter-web of web

Because of the import of dart:io via the import chain package:disk_lru_cache/disk_lru_cache.dart->package:disk_lru_cache/_src/ioutil.dart->dart:io

Health suggestions

Fix lib/_src/disk_lru_cache.dart. (-2.48 points)

Analysis of lib/_src/disk_lru_cache.dart reported 5 hints:

line 5 col 8: Unused import: 'dart:ui'.

line 9 col 8: Unused import: 'package:flutter/foundation.dart'.

line 10 col 8: Unused import: 'package:flutter/material.dart'.

line 54 col 8: The value of the field '_hasRecordError' isn't used.

line 66 col 8: The value of the field '_mostRecentTrimFailed' isn't used.

Maintenance suggestions

The package description is too short. (-20 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.48.0 <3.0.0
flutter 0.0.0
synchronized ^2.1.1 2.2.0+1
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8 1.2.0
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8
Dev dependencies
http any