분류, 패키지 및 저장소 검색

패키지 상세v7.0.0

network_to_file_image

존재하는 경우 로컬 이미지 파일을 엽니다. 없으면 네트워크에서 이미지를 가져와 다음 사용을 위해 로컬 파일에 저장합니다.

AndroidiOSmacOSWindowsLinux
30일 다운로드
1.5천
좋아요
185
Pub 점수
140

패키지 설치

flutter pub add network_to_file_image

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

먼저 로컬 파일을 확인하여 이미지 로딩을 효율적으로 관리하는 플러터 패키지입니다. 이미지가 로컬에 없으면 네트워크에서 다운로드하여 디스크에 저장해 향후 사용하기 위해 활용함으로써 중복 다운로드를 줄이고 성능을 향상시킵니다. 최소한의 설정으로 지속적인 이미지 캐싱이 필요한 앱에 적합합니다.

사용 사례

  • 오프라인 액세스를 위한 원격 이미지 캐싱
  • 반복적인 네트워크 요청 줄이기
  • 로컬 저장소를 통한 앱 성능 향상
  • 사용자 프로필 사진을 표시하고 대체 옵션 제공
  • 지속성과 함께 목록 뷰에서 이미지 로드

주요 기능

  • 네트워크 가져오기 전 로컬 파일 확인
  • 다운로드 후 자동 이미지 저장
  • 내장 캐싱 메커니즘
  • 다수의 플랫폼을 지원합니다
  • 간단한 API 통합

적합한 대상

  • 오프라인 이미지 사용이 필요한 앱
  • 이미지 중심 애플리케이션
  • 경량 캐싱을 찾는 개발자
  • 제한된 백엔드 인프라를 갖춘 프로젝트
  • 모바일 및 데스크톱 플랫폼 대상 앱

고려 사항

  • 일부 플랫폼에서는 파일 시스템 권한이 필요합니다
  • 디스크 공간 사용량은 시간이 지남에 따라 증가합니다
  • 내장된 만료 또는 정리 전략 없음
  • 수동 캐시 관리가 필요할 수 있습니다
  • 캐시 크기 또는 TTL에 대한 제어가 제한됨

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

pub package

network_to_file_image

This package combines NetworkImage and FileImage to:

  • Download the image once from the URL,
  • Save it to the local file system,
  • Use the saved image from the file system from then on.

In more detail:

Given a file and url of an image, it first tries to read it from the local file. It decodes the given File object as an image, associating it with the given scale.

However, if the image doesn't yet exist as a local file, it fetches the given URL from the network, associating it with the given scale, and then saves it to the local file. The image will be cached regardless of cache headers from the server.

Notes:
  • If the provided url is null or empty, NetworkToFileImage will default to FileImage. It will read the image from the local file, and won't try to download it from the network.

  • If the provided file is null, NetworkToFileImage will default to NetworkImage. It will download the image from the network, and won't save it locally.

Use the package

Import path_provider in your pubspec.yaml file:

path_provider: ^2.1.1 

Then use it to create a File from a file name:

Future<File> file(String filename) async {
  Directory dir = await getApplicationDocumentsDirectory();
  String pathName = p.join(dir.path, filename);
  return File(pathName);
}

var myFile = await file("myFileName.png"),

Then, create the image:

Image(image: 
   NetworkToFileImage(
      url: "https://example.com/someFile.png", 
      file: myFile,
   )
)

If you make debug: true it prints to the console whether the image was read from the file or fetched from the network:

Image(image: 
   NetworkToFileImage(
      url: "https://example.com/someFile.png", 
      file: myFile, 
      debug: true,
   )
)    

Try running the NetworkToFileImage example.

Important:

The directory where you want to save the image must already exist in the local disk. Otherwise, the image won't be saved.

Canvas

You can also load images to use with the Canvas object of the paint method of a CustomPainter.

ImageProviders can't be used directly with the Canvas object, but you can use the provided ImageForCanvas class.

For example: Suppose a User object that contains url and filename properties:

var imageForCanvas = ImageForCanvas<User>(
        imageProviderSupplier: (User user) => NetworkToFileImage(file: user.file, url: user.url),
        keySupplier: (User user) => user.filename,
        loadCallback: (image, obj, key) => setState((){}),
      );

// While the image is downloading, this will return null.
var myImage = imageForCanvas.image(user);

if (myImage != null) {
    canvas.drawImage(myImage, ...);
    }

It will use the regular image cache from Flutter, and works not only with NetworkToFileImage provider, but any other image providers.

Try running the ImageForCanvas example.

Tests

You can set mock files (local and in the network). Please see methods:

  • setMockFile(File file, Uint8List bytes)
  • setMockUrl(String url, Uint8List bytes)
  • clearMocks()
  • clearMockFiles()
  • clearMockUrls()

Your mocked urls are usually only seen by the NetworkToFileImage class. However, you may override the default Dart http methods so that these urls are visible to other ImageProviders.

To that end, simply call this method:

NetworkToFileImage.startHttpOverride();

You can stop the http override by calling:

NetworkToFileImage.stopHttpOverride();

By Marcelo Glasberg

glasberg.dev
github.com/marcglasberg
linkedin.com/in/marcglasberg/
twitter.com/glasbergmarcelo
stackoverflow.com/users/3411681/marcg
medium.com/@marcglasberg

My article in the official Flutter documentation:

The Flutter packages I've authored:

My Medium Articles:

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.