Biblioteca de cache HTTP para Flutter Dio, semelhante ao RxCache. Usa o sqflite como cache em disco e a estratégia LRU do google/quiver-dart como cache em memória.
Orientação gerada a partir de informações públicas. Apenas para referência.
O Dio HTTP Cache é uma biblioteca de cache para o cliente HTTP Dio do Flutter, oferecendo cache em memória e baseado em disco. Ele utiliza o sqflite para armazenamento persistente no disco e implementa uma estratégia LRU (Least Recently Used) por meio do google/quiver-dart para gerenciamento eficiente da memória. Este pacote ajuda a reduzir solicitações de rede redundantes, melhorar o desempenho do aplicativo e economizar largura de banda ao armazenar em cache respostas HTTP. Ideal para aplicativos que exigem suporte offline ou chamadas frequentes a APIs com dados estáveis.
Casos de uso
Armazenar em cache respostas da API para reduzir o uso de rede
Habilitar o acesso offline a dados anteriormente buscados
Melhorando o desempenho do aplicativo com latência reduzida
Armazenar dados frequentemente acessados de forma eficiente
Redução da carga do servidor por meio de respostas em cache
Principais recursos
Cache em disco usando sqflite
Cache de memória LRU com quiver-dart
Cache automático de solicitação/resposta
Expiração de cache configurável
Suporta solicitações GET e HEAD
Indicado para
Aplicativos com chamadas de API frequentes
Aplicações com capacidade offline
Camadas de rede otimizadas para desempenho
Aplicativos móveis com grande volume de dados
Desenvolvedores usando o Dio para requisições HTTP
Considerações
Requer configuração e permissões do sqflite
O tamanho do cache deve ser gerenciado manualmente
Não adequado para grandes dados binários
Limitado aos métodos GET/HEAD
Pode ser necessário lógica personalizada de chave de cache para solicitações complexas
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
If getting data from network succeeds, store or refresh cache.
If getting data from network fails or no network avaliable, try get data from cache instead of an error.
Use "CacheConfig" to config default params
baseUrl: it’s optional; If you don't have set baseUrl in CacheConfig, when you call deleteCache, you need provide full path like "https://www.google.com/search?q=hello", but not just "search?q=hello".
encrypt / decrypt: these two must be used together to encrypt the disk cache data, you can also zip data here.
defaultMaxAge: use Duration(day:7) as default.
defaultaMaxStale: similar with DefaultMaxAge.
databasePath: database path.
databaseName: database name.
skipMemoryCache: false defalut.
skipDiskCache: false default.
maxMemoryCacheCount: 100 defalut.
defaultRequestMethod: use "POST" as default, it will be used in delete caches.
diskStore: custom disk storage.
How to clear expired cache
Just ignore it, that is automatic.
But if you insist : DioCacheManager.clearExpired();
How to delete caches
No matter what subKey is, delete local cache if primary matched.
// Automatically parses primarykey from path
_dioCacheManager.deleteByPrimaryKey(path, requestMethod: "POST");
Delete local cache when both primaryKey and subKey matched.
// delete local cache when both primaryKey and subKey matched.
_dioCacheManager.deleteByPrimaryKeyAndSubKey(path, requestMethod: "GET");
INPORTANT: If you have additional parameters when requesting the http interface, you must take them with it, for example:
0 ~ 3 days : Return data from cache directly (irrelevant with network).
3 ~ 7 days:
Get data from network first.
If getting data from network succeeds, refresh cache.
If getting data from network fails or no network avaliable, try get data from cache instead of an error.
7 ~ ∞ days: It won't use cache anymore, and the cache will be deleted at the right time.
License
Copyright2019HurshiLicensed under the ApacheLicense, Version2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0Unlessrequired by applicable law or agreed to in writing, software
distributed under the Licenseis distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the Licensefor the specific language governing permissions and
limitations under the License.