Flutter 實現圖片快取到本地
阿新 • • 發佈:2018-12-30
網上可能有很多實現的外掛,有些動不動就上千行程式碼, 其實很簡單 只需要在原始碼的基礎上加一個本地快取就行,
畢竟原始碼是最可靠的
https://github.com/dikeboy/flutter-cache-image-local
Flutter 自帶的有2個 圖片的Widget ,Image 和FadeInImage, 從字面上就能理解 FadeIn是多了個預載入的圖,
FadeInImage 有兩個 方法 ,memoryNetwork 和assertNetwork 預載入圖來源於二進位制 或者 assert,如果是動態生成的 就需要用memoryNetwork
網路圖片是通過NetworkImage來實現載入,
檔案 assert memory networkImage 都是繼承自Image_provider,
Image_provider本身已經帶了一個記憶體快取,大概就類似安卓的Lrucache
ImageStream resolve(ImageConfiguration configuration) { assert(configuration != null); final ImageStream stream = ImageStream(); T obtainedKey; obtainKey(configuration).then<void>((T key) { obtainedKey = key; stream.setCompleter(PaintingBinding.instance.imageCache.putIfAbsent(key, () => load(key)));
這裡的imageCache就是Flutter 自帶的快取
我們要實現快取到本地 肯定需要 在記憶體快取之後 網路請求之前
先來看下NetworkImage的原始碼
class NetworkImage extends ImageProvider<NetworkImage> {/// Creates an object that fetches the image at the given URL. /// /// The arguments must not be null. const NetworkImage(this.url, { this.scale = 1.0 , this.headers }) : assert(url != null), assert(scale != null); /// The URL from which the image will be fetched. final String url; /// The scale to place in the [ImageInfo] object of the image. final double scale; /// The HTTP headers that will be used with [HttpClient.get] to fetch image from network. final Map<String, String> headers; @override Future<NetworkImage> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<NetworkImage>(this); } @override ImageStreamCompleter load(NetworkImage key) { return MultiFrameImageStreamCompleter( codec: _loadAsync(key), //這個就是主要的圖片網路載入方法 , 我們主要是需要修改這個方法 scale: key.scale, informationCollector: (StringBuffer information) { information.writeln('Image provider: $this'); information.write('Image key: $key'); } ); } static final HttpClient _httpClient = HttpClient(); 方法很簡單,拿回資料 轉換為二進位制返回/ Future<ui.Codec> _loadAsync(NetworkImage key) async { assert(key == this); final Uri resolved = Uri.base.resolve(key.url); final HttpClientRequest request = await _httpClient.getUrl(resolved); headers?.forEach((String name, String value) { request.headers.add(name, value); }); final HttpClientResponse response = await request.close(); if (response.statusCode != HttpStatus.ok) throw Exception('HTTP request failed, statusCode: ${response?.statusCode}, $resolved'); final Uint8List bytes = await consolidateHttpClientResponseBytes(response); if (bytes.lengthInBytes == 0) throw Exception('NetworkImage is an empty file: $resolved'); return await PaintingBinding.instance.instantiateImageCodec(bytes); } @override bool operator ==(dynamic other) { if (other.runtimeType != runtimeType) return false; final NetworkImage typedOther = other; return url == typedOther.url && scale == typedOther.scale; } @override int get hashCode => hashValues(url, scale); @override String toString() => '$runtimeType("$url", scale: $scale)'; }
這裡需要引入 幾個外掛 其實這幾個就算不修改這裡 專案中肯定也是必須的
http: ^0.12.0 網路請求 這個毫無疑問
transparent_image: ^0.1.0 //這是一個預載入的透明圖 ,如果需要用assert圖或者是自定義可以不需要 這裡為了方便
path_provider: ^0.4.1 //這是獲取 安卓 IOS 檔案快取路徑
crypto: ^2.0.6 //這個主要是MD5 base64之類 轉碼 我們根據圖片的md5(url)做為key來快取
下面直接貼修改後的 NetworkImage
class MyNetworkImage extends ImageProvider<MyNetworkImage> { /// Creates an object that fetches the image at the given URL. /// /// The arguments must not be null. const MyNetworkImage(this.url, { this.scale = 1.0 , this.headers,this.sdCache }) : assert(url != null), assert(scale != null); /// The URL from which the image will be fetched. final String url; final bool sdCache; //加一個標誌為 是否需要快取到sd卡 /// The scale to place in the [ImageInfo] object of the image. final double scale; /// The HTTP headers that will be used with [HttpClient.get] to fetch image from network. final Map<String, String> headers; @override Future<MyNetworkImage> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<MyNetworkImage>(this); } @override ImageStreamCompleter load(MyNetworkImage key) { return MultiFrameImageStreamCompleter( codec: _loadAsync(key), scale: key.scale, informationCollector: (StringBuffer information) { information.writeln('Image provider: $this'); information.write('Image key: $key'); } ); } Future<Codec> _loadAsync(MyNetworkImage key) async { assert(key == this);
//本地已經快取過就直接返回圖片 if(sdCache!=null){ final Uint8List bytes =await _getFromSdcard(key.url); if (bytes!=null&&bytes.lengthInBytes!=null&&bytes.lengthInBytes!= 0) { print("success"); return await PaintingBinding.instance.instantiateImageCodec(bytes); } } final Uri resolved = Uri.base.resolve(key.url); http.Response response = await http.get(resolved); if (response.statusCode != HttpStatus.ok) throw Exception('HTTP request failed, statusCode: ${response?.statusCode}, $resolved'); final Uint8List bytes = await response.bodyBytes;
//網路請求結束後快取圖片到本地 if(sdCache!=null&&bytes.lengthInBytes != 0){ _saveToImage(bytes, key.url); } if (bytes.lengthInBytes == 0) throw Exception('MyNetworkImage is an empty file: $resolved'); return await PaintingBinding.instance.instantiateImageCodec(bytes); } @override bool operator ==(dynamic other) { if (other.runtimeType != runtimeType) return false; final MyNetworkImage typedOther = other; return url == typedOther.url && scale == typedOther.scale; } @override int get hashCode => hashValues(url, scale); @override String toString() => '$runtimeType("$url", scale: $scale)'; 圖片路徑MD5一下 快取到本地 void _saveToImage(Uint8List mUint8List,String name) async { name = md5.convert(convert.utf8.encode(name)).toString(); Directory dir = await getTemporaryDirectory(); String path = dir.path +"/"+name; var file = File(path); bool exist = await file.exists(); print("path =${path}"); if(!exist) File(path).writeAsBytesSync(mUint8List); } _getFromSdcard(String name) async{ name = md5.convert(convert.utf8.encode(name)).toString(); Directory dir = await getTemporaryDirectory(); String path = dir.path +"/"+name; var file = File(path); bool exist = await file.exists(); if(exist){ final Uint8List bytes = await file.readAsBytes(); return bytes; } return null; } }
如果需要直接修改FadeInImage 或者Image 直接把程式碼烤到一個新的dart檔案 把NetworkImage 全部改成MyNetworkImage就行了