Cache json map to local file with Dart:io. Read file with sync api.

Overview

local_cache_sync

一个非常简单易用的Flutter本地储存库,适用于在本地储存一列轻量数据(例如用户保存在本地的设备信息,或者缓存一系列用户信息)。

local_cache_sync的所有方法都是同步,而不是异步的。这意味着你不需要使用await就可以获取数据。在flutter中,这可以显著减少StatefulWidget的数量,大量减少代码的复杂度。

Start

pubspec.yaml

  path_provider: ^1.4.5
  local_cache_sync: ^1.2.1

Set Cache Path.

After 1.2.0:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  LocalCacheSync.instance.setCachePath(
    await getTemporaryDirectory(),
    'example_app/',
  );
  runApp(MyApp());
}

Before(less than or equal to 1.1.1):

getTemporaryDirectory().then((uri) {
      LocalCacheSync.instance.setCachePath(uri.path);
});

User Default Demo

Switch组件的值会被缓存到本地,即使重新启动App也会保留

使用local_cache_sync保存与读取参数都是同步的,这意味着赋值即是保存,而且在StatelessWidget中,可以立即使用数据。

基础用法

Switch(
  value: LocalCacheSync.userDefault.getWithKey<bool>('switch-A'),
  onChanged: (v) {
    setState(() {
      LocalCacheSync.userDefault.setWithKey<bool>('switch-A', v);
    });
  },
),

更方便的使用方法(推荐)

// Creat class:
class MySetting {
  static var autoLogin = const DefaultValueCache<bool>('autoLogin', false);
}
// build
Switch(
  value: MySetting.autoLogin.value,
  onChanged: (v) {
    setState(()=>MySetting.autoLogin.value = v);
  },
),

Usage: User Default Cache 用户偏好设置缓存

使用local_cache_sync实现保存用户自定义设置非常简单,只需要赋值与取值,无需异步等待,即可保存参数到本地。
读取参数也是同步的,这意味着你可以在StatelessWidget中立即使用数据。

Use Function:

Save values

LocalCacheSync.userDefault.setWithKey<bool>('isDarkMode',true);
LocalCacheSync.userDefault.setWithKey<String>('token','aabbccdd');
LocalCacheSync.userDefault.setWithKey<Map>('x-config',{'id':1243});

Read values

var res = LocalCacheSync.userDefault.getWithKey<bool>('isDarkMode');
var res = LocalCacheSync.userDefault.getWithKey<String>('token');
var res = LocalCacheSync.userDefault.getWithKey<Map>('x-config');

Use operator:

Save values

LocalCacheSync.userDefault['isDarkMode'] = true;
LocalCacheSync.userDefault['token'] = 'aabbccdd';
LocalCacheSync.userDefault['x-config'] = {'id':1243};

Read values

bool res = LocalCacheSync.userDefault['isDarkMode'];
String res = LocalCacheSync.userDefault['token'];
Map res = LocalCacheSync.userDefault['x-config'];

DefaultValueCache

Eazy used with static property. 只需要静态属性就可以使用缓存,并为缓存指定默认值,不担心缓存为空。

// Creat class:
class ProjectCustomUserDefault {
  static var autoLogin = const DefaultValueCache<bool>('autoLogin', false);
}

// save
ProjectCustomUserDefault.autoLogin.value = true;
// read
bool isAutoLogin = ProjectCustomUserDefault.autoLogin.value

Usage: Table Cache 列表管理

如果你需要管理一系列值,请使用LocalCacheLoader,只需要一个channel标志,你就可以管理一系列值。

Lazy Load

LocalCacheLoader在内部实现了懒加载的效果:只有取value属性时数据才真正被加载。

在应用中,假如你有1-100号设备显示在Listview.builder中,只有100号设备即将进入屏幕中时,100号设备的缓存参数才会被真正加载。也就是说LocalCacheLoader不会导致长列表卡顿。

Model Example

我推荐你这样创建你的model:
Create class load from loader.

class Device {
  final String uuid;
  final String name;
  final int type;

  Device({
    this.uuid,
    this.name,
    this.type,
  });

  Device.fromJson(Map<String, dynamic> map)
      : this(
          uuid: map['uuid'],
          name: map['name'],
          type: map['type'],
        );

  static LocalCacheLoader get _loader => LocalCacheLoader('device');

  static List<Device> all() {
    return _loader.all
        .map<Device>(
          (cache) => Device.fromJson(cache.value),
        )
        .toList();
  }

  // LocalCacheObject仅在取出Value时进行数据加载
  // 在数据很大时,这样可以提升列表加载性能
  static List<LocalCacheObject> allWithLazyLoad() {
    return _loader.all;
  }

  LocalCacheObject save() {
    return Device._loader.saveById(uuid, jsonMap);
  }

  Map<String, dynamic> get jsonMap => {
        'uuid': uuid,
        'name': name,
        'type': type,
      };
}

你也可以另外封装loader来读写其他信息,对于轻量级的储存,以上是非常简单易用的。

Cache Detail Overview

可以快速查看保存的数据:

LocalCacheSync.pushDetailPage(context)

警告

不要在io密集型场景使用local_cache_sync,例如即时储存每秒10次的扫描结果。
虽然flutter中阻塞主线程不会导致UI卡顿,但是你仍不应当在io密集型场景使用,这超出了local_cache_sync设计的工作范围。

致谢

图片缓存功能修改自:https://github.com/pedia/file_cache 。感谢原作者的贡献。

You might also like...

Provide route generator to create route map quickly by annotations.

ff_annotation_route Languages: English | 中文简体 Description Provide a route generator to create route map quickly by annotations. ff_annotation_route De

Nov 25, 2022

Flutter Map plugin for ArcGIS Esri. Currently support feature layer (point, polygon)

Flutter Map plugin for ArcGIS Esri Currently support feature layer(point, polygon, polyline coming soon) We are working on more features A Dart implem

Nov 9, 2022

Simply extract required values from specific paths in a Map or a List

extract values from Map/List using dot-seprated strings you don't have to cast multiple times to fetch a simple values, this is very useful while working with i.e json data

Nov 18, 2022

Your best flutter coding friend. All in one; state management, navigation management(with dynamic routing), local storage, localization, dependency injection, cool extensions with best usages and with the support of best utilities!

okito Your best flutter coding friend. All in one; state management, navigation management(with dynamic routing), local storage, dependency injection,

Jul 10, 2022

A generator to create config class from json files that support many environments

A generator to create config class from json files that support many environments. Motivation If you use a json file to config your applications, perp

Oct 9, 2021

A flutter package that allows you to transform your excel to json

excel_to_json A package that allows you to transform your excel to the following format: Excel To JSON Getting Started At current the package allows y

Nov 7, 2022

A flutter application , that create dynamic forms from json data

checktyper A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

Aug 23, 2022

Generates utilities to aid in serializing to/from JSON.

Provides Dart Build System builders for handling JSON. json_serializable Package: https://pub.dev/packages/json_serializable Source code The core pack

Jan 8, 2023

Dart R-file generator for build_runner

r_resources This package is made for R-file code generation using build_runner.

Dec 17, 2021
Owner
null
Flutter's sync log component implementation by DartNative.

Flutter's sync log component implementation by DartNative

DartNative 3 Apr 30, 2022
Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object

Lazy JSON Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object and JSON array. Getting started

Kinnara Digital Studio 0 Oct 27, 2021
A simple way to cache values that result from rather expensive operations.

cached_value A simple way to cache values that result from rather expensive operations. It is useful to cache values that: Are computed from other val

Renan 27 Nov 11, 2022
A CLI tool to help generate dart classes from json returned from API

Json 2 Dart Command line utility Important note There is already a package called json2dart so this package will be called json2dartc ! This project w

Adib Mohsin 38 Oct 5, 2022
JSON API parser for Flutter

Flutter Japx - JSON:API Decoder/Encoder Lightweight [JSON:API][1] parser that flattens complex [JSON:API][1] structure and turns it into simple JSON a

Infinum 23 Dec 20, 2022
An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization.

AutoMapper for Dart An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization. Examp

Leynier Gutiérrez González 7 Aug 24, 2022
From JSON to Dart Advanced

From JSON to Dart Advanced Table of Contents Features Convert from clipboard Convert from selection Convert from clipboard to code generation Convert

 нιяαитнα 80 Dec 17, 2022
Args simple - A simple argument parser and handler, integrated with JSON and dart

args_simple A simple argument parser and handler, integrated with JSON and dart:

Graciliano Monteiro Passos 1 Jan 22, 2022
This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON

This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON. Why? Compatible with all target plat

Alexander Mazuruk 356 Jan 6, 2023
A mobile map based application to help people everywhere around the world get help

Wonder This is a mobile application made by flutter. The application is called "Wonder" because it will help people everywhere around the world to get

Sara Nersisian 1 Dec 2, 2021