disk_lru_cache 0.0.1

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • new22

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');
    if(editor!=null){
      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);
    print(str);

With bytes

// write bytes
  CacheEditor editor = await cache.edit('imagekey');
  if(editor!=null){
    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);
    print(bytes);
  }

[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.

example/lib/main.dart

import 'dart:async';
import 'dart:io';

import 'dart:math' as Math;
import 'package:flutter/material.dart';

import 'package:disk_lru_cache/disk_lru_cache.dart';
import 'test_disk_cache.dart';

void main() async {
  await testCache();
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  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;

  @override
  _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.
      _counter++;
    });
  }

  @override
  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(
              '$_counter',
              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:


dependencies:
  disk_lru_cache: ^0.0.1

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or flutter packages 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';
  
Version Uploaded Documentation Archive
0.0.1 Sep 9, 2018 Go to the documentation of disk_lru_cache 0.0.1 Download disk_lru_cache 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
0
Health:
Code health derived from static analysis. [more]
48
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
40
Overall:
Weighted score of the above. [more]
22
Learn more about scoring.

We analyzed this package on Sep 21, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.3
  • Flutter: 0.8.4

Platforms

Detected platforms: unsure

Error(s) prevent platform classification:

Error(s) in lib/_src/disk_lru_cache.dart: Target of URI doesn't exist: 'package:http/http.dart'.

Issues and suggestions

Fix platform conflict in lib/_src/disk_lru_cache.dart.

Make sure that the imported libraries are not in conflict. Error(s) in lib/_src/disk_lru_cache.dart: Target of URI doesn't exist: 'package:http/http.dart'.

Fix platform conflicts.

Error(s) prevent platform classification:

Error(s) in lib/_src/disk_lru_cache.dart: Target of URI doesn't exist: 'package:http/http.dart'.

Running dartdoc failed.

Make sure dartdoc runs without any issues.

The description is too short.

Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

Package is pre-v0.1 release.

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

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.48.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11
meta 1.1.6
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test