您好,登錄后才能下訂單哦!
這篇文章主要講解了“Flutter加載圖片流程之ImageCache源碼分析”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Flutter加載圖片流程之ImageCache源碼分析”吧!
const int _kDefaultSize = 1000; const int _kDefaultSizeBytes = 100 << 20; // 100 MiB /// Class for caching images. /// /// Implements a least-recently-used cache of up to 1000 images, and up to 100 /// MB. The maximum size can be adjusted using [maximumSize] and /// [maximumSizeBytes]. /// /// The cache also holds a list of 'live' references. An image is considered /// live if its [ImageStreamCompleter]'s listener count has never dropped to /// zero after adding at least one listener. The cache uses /// [ImageStreamCompleter.addOnLastListenerRemovedCallback] to determine when /// this has happened. /// /// The [putIfAbsent] method is the main entry-point to the cache API. It /// returns the previously cached [ImageStreamCompleter] for the given key, if /// available; if not, it calls the given callback to obtain it first. In either /// case, the key is moved to the 'most recently used' position. /// /// A caller can determine whether an image is already in the cache by using /// [containsKey], which will return true if the image is tracked by the cache /// in a pending or completed state. More fine grained information is available /// by using the [statusForKey] method. /// /// Generally this class is not used directly. The [ImageProvider] class and its /// subclasses automatically handle the caching of images. /// /// A shared instance of this cache is retained by [PaintingBinding] and can be /// obtained via the [imageCache] top-level property in the [painting] library. /// /// {@tool snippet} /// /// This sample shows how to supply your own caching logic and replace the /// global [imageCache] variable.
ImageCache類是一個用于緩存圖像的類。它實現了一個最近最少使用的緩存,最多緩存1000個圖像,最大緩存100MB。緩存的最大大小可以使用maximumSize和maximumSizeBytes進行調整。
ImageCache還持有一個"活"圖像引用的列表。當ImageStreamCompleter的監聽計數在添加至少一個監聽器后從未降至零時,圖像被認為是"活"的。緩存使用ImageStreamCompleter.addOnLastListenerRemovedCallback方法來確定這種情況是否發生。
putIfAbsent方法是緩存API的主要入口點。如果給定鍵的先前緩存中有ImageStreamCompleter可用,則返回該實例;否則,它將首先調用給定的回調函數來獲取該實例。在任何情況下,鍵都會被移到"最近使用"的位置。
調用者可以使用containsKey方法確定圖像是否已經在緩存中。如果圖像以待處理或已處理狀態被緩存,containsKey將返回true。使用statusForKey方法可以獲得更細粒度的信息。
通常情況下,這個類不會直接使用。ImageProvider類及其子類會自動處理圖像緩存。
在PaintingBinding中保留了這個緩存的共享實例,并可以通過painting庫中的imageCache頂級屬性獲取。
final Map<Object, _PendingImage> _pendingImages = <Object, _PendingImage>{}; final Map<Object, _CachedImage> _cache = <Object, _CachedImage>{}; /// ImageStreamCompleters with at least one listener. These images may or may /// not fit into the _pendingImages or _cache objects. /// /// Unlike _cache, the [_CachedImage] for this may have a null byte size. final Map<Object, _LiveImage> _liveImages = <Object, _LiveImage>{};
這段代碼定義了三個 Map
對象來實現圖片的緩存機制。其中:
_pendingImages
:用于緩存正在加載中的圖片,鍵為圖片的標識符,值為 _PendingImage
對象。
_cache
:用于緩存已經加載完成的圖片,鍵為圖片的標識符,值為 _CachedImage
對象。
_liveImages
:用于緩存當前正在使用中的圖片,即其對應的 ImageStreamCompleter
對象有至少一個監聽器。鍵為圖片的標識符,值為 _LiveImage
對象。
需要注意的是,_liveImages
中的 _LiveImage
對象的 byteSize
可能為 null
,而 _cache
中的 _CachedImage
對象的 byteSize
總是非空的。這是因為 _cache
中的圖片已經加載完成并占用了內存,而 _liveImages
中的圖片可能還處于加載中或者被釋放了內存,因此其大小可能還未確定或者已經變為 null
。
/// Maximum number of entries to store in the cache. /// /// Once this many entries have been cached, the least-recently-used entry is /// evicted when adding a new entry. int get maximumSize => _maximumSize; int _maximumSize = _kDefaultSize; /// Changes the maximum cache size. /// /// If the new size is smaller than the current number of elements, the /// extraneous elements are evicted immediately. Setting this to zero and then /// returning it to its original value will therefore immediately clear the /// cache. set maximumSize(int value) { assert(value != null); assert(value >= 0); if (value == maximumSize) { return; } TimelineTask? timelineTask; if (!kReleaseMode) { timelineTask = TimelineTask()..start( 'ImageCache.setMaximumSize', arguments: <String, dynamic>{'value': value}, ); } _maximumSize = value; if (maximumSize == 0) { clear(); } else { _checkCacheSize(timelineTask); } if (!kReleaseMode) { timelineTask!.finish(); } } /// The current number of cached entries. int get currentSize => _cache.length; /// Maximum size of entries to store in the cache in bytes. /// /// Once more than this amount of bytes have been cached, the /// least-recently-used entry is evicted until there are fewer than the /// maximum bytes. int get maximumSizeBytes => _maximumSizeBytes; int _maximumSizeBytes = _kDefaultSizeBytes; /// Changes the maximum cache bytes. /// /// If the new size is smaller than the current size in bytes, the /// extraneous elements are evicted immediately. Setting this to zero and then /// returning it to its original value will therefore immediately clear the /// cache. set maximumSizeBytes(int value) { assert(value != null); assert(value >= 0); if (value == _maximumSizeBytes) { return; } TimelineTask? timelineTask; if (!kReleaseMode) { timelineTask = TimelineTask()..start( 'ImageCache.setMaximumSizeBytes', arguments: <String, dynamic>{'value': value}, ); } _maximumSizeBytes = value; if (_maximumSizeBytes == 0) { clear(); } else { _checkCacheSize(timelineTask); } if (!kReleaseMode) { timelineTask!.finish(); } } /// The current size of cached entries in bytes. int get currentSizeBytes => _currentSizeBytes; int _currentSizeBytes = 0;
maximumSize
和maximumSizeBytes
用于控制緩存的大小。maximumSize
是緩存中最多可以存儲的元素數,超出該限制時,添加新的元素會導致最近最少使用的元素被清除。maximumSizeBytes
是緩存中最多可以存儲的字節數,超出該限制時,添加新元素會導致最近最少使用的元素被清除,直到緩存中元素的字節總數小于最大值。currentSize
和currentSizeBytes
分別表示當前緩存中元素的數量和字節總數。在緩存大小發生變化時,會自動清除多出的元素。
/// Evicts all pending and keepAlive entries from the cache. /// /// This is useful if, for instance, the root asset bundle has been updated /// and therefore new images must be obtained. /// /// Images which have not finished loading yet will not be removed from the /// cache, and when they complete they will be inserted as normal. /// /// This method does not clear live references to images, since clearing those /// would not reduce memory pressure. Such images still have listeners in the /// application code, and will still remain resident in memory. /// /// To clear live references, use [clearLiveImages]. void clear() { if (!kReleaseMode) { Timeline.instantSync( 'ImageCache.clear', arguments: <String, dynamic>{ 'pendingImages': _pendingImages.length, 'keepAliveImages': _cache.length, 'liveImages': _liveImages.length, 'currentSizeInBytes': _currentSizeBytes, }, ); } for (final _CachedImage image in _cache.values) { image.dispose(); } _cache.clear(); for (final _PendingImage pendingImage in _pendingImages.values) { pendingImage.removeListener(); } _pendingImages.clear(); _currentSizeBytes = 0; }
clear()
方法用于清除ImageCache中所有的待定和保持活動狀態的圖像緩存。這對于需要獲取新圖像的情況非常有用,例如根資產包已更新。尚未完成加載的圖像不會從緩存中刪除,當它們完成時,它們將像往常一樣被插入。
此方法不清除圖像的活動引用,因為這樣做不會減少內存壓力。這些圖像仍然在應用程序代碼中具有偵聽器,并且仍將保留在內存中。如果要清除活動引用,請使用clearLiveImages()
方法。
/// Evicts a single entry from the cache, returning true if successful. /// /// Pending images waiting for completion are removed as well, returning true /// if successful. When a pending image is removed the listener on it is /// removed as well to prevent it from adding itself to the cache if it /// eventually completes. /// /// If this method removes a pending image, it will also remove /// the corresponding live tracking of the image, since it is no longer clear /// if the image will ever complete or have any listeners, and failing to /// remove the live reference could leave the cache in a state where all /// subsequent calls to [putIfAbsent] will return an [ImageStreamCompleter] /// that will never complete. /// /// If this method removes a completed image, it will _not_ remove the live /// reference to the image, which will only be cleared when the listener /// count on the completer drops to zero. To clear live image references, /// whether completed or not, use [clearLiveImages]. /// /// The `key` must be equal to an object used to cache an image in /// [ImageCache.putIfAbsent]. /// /// If the key is not immediately available, as is common, consider using /// [ImageProvider.evict] to call this method indirectly instead. /// /// The `includeLive` argument determines whether images that still have /// listeners in the tree should be evicted as well. This parameter should be /// set to true in cases where the image may be corrupted and needs to be /// completely discarded by the cache. It should be set to false when calls /// to evict are trying to relieve memory pressure, since an image with a /// listener will not actually be evicted from memory, and subsequent attempts /// to load it will end up allocating more memory for the image again. The /// argument must not be null. /// /// See also: /// /// * [ImageProvider], for providing images to the [Image] widget. bool evict(Object key, { bool includeLive = true }) { assert(includeLive != null); if (includeLive) { // Remove from live images - the cache will not be able to mark // it as complete, and it might be getting evicted because it // will never complete, e.g. it was loaded in a FakeAsync zone. // In such a case, we need to make sure subsequent calls to // putIfAbsent don't return this image that may never complete. final _LiveImage? image = _liveImages.remove(key); image?.dispose(); } final _PendingImage? pendingImage = _pendingImages.remove(key); if (pendingImage != null) { if (!kReleaseMode) { Timeline.instantSync('ImageCache.evict', arguments: <String, dynamic>{ 'type': 'pending', }); } pendingImage.removeListener(); return true; } final _CachedImage? image = _cache.remove(key); if (image != null) { if (!kReleaseMode) { Timeline.instantSync('ImageCache.evict', arguments: <String, dynamic>{ 'type': 'keepAlive', 'sizeInBytes': image.sizeBytes, }); } _currentSizeBytes -= image.sizeBytes!; image.dispose(); return true; } if (!kReleaseMode) { Timeline.instantSync('ImageCache.evict', arguments: <String, dynamic>{ 'type': 'miss', }); } return false; }
從緩存中刪除一個條目,如果成功則返回true。
同時刪除等待完成的待處理圖像,如果成功則返回true。當刪除待處理的圖像時,也將移除其上的監聽器,以防止其在最終完成后添加到緩存中。
如果此方法刪除了待處理的圖像,則它還將刪除圖像的相應實時跟蹤,因為此時無法確定圖像是否會完成或具有任何偵聽器,并且未刪除實時引用可能會使緩存處于狀態,其中所有后續對 [putIfAbsent] 的調用都將返回一個永遠不會完成的 [ImageStreamCompleter]。
如果此方法刪除了已完成的圖像,則不會刪除圖像的實時引用,只有在監聽器計數為零時才會清除實時圖像引用。要清除已完成或未完成的實時圖像引用,請使用 [clearLiveImages]。
key
必須等于用于在 [ImageCache.putIfAbsent] 中緩存圖像的對象。
如果 key 不是立即可用的對象(這很常見),請考慮使用 [ImageProvider.evict] 間接調用此方法。
includeLive
參數確定是否也應將仍具有樹中偵聽器的圖像清除。在圖像可能損壞并需要完全丟棄緩存的情況下,應將此參數設置為true。在嘗試緩解內存壓力的情況下,應將其設置為false,因為具有偵聽器的圖像實際上不會從內存中清除,后續嘗試加載它將再次為圖像分配更多內存。該參數不能為空。
/// Updates the least recently used image cache with this image, if it is /// less than the [maximumSizeBytes] of this cache. /// /// Resizes the cache as appropriate to maintain the constraints of /// [maximumSize] and [maximumSizeBytes]. void _touch(Object key, _CachedImage image, TimelineTask? timelineTask) { assert(timelineTask != null); if (image.sizeBytes != null && image.sizeBytes! <= maximumSizeBytes && maximumSize > 0) { _currentSizeBytes += image.sizeBytes!; _cache[key] = image; _checkCacheSize(timelineTask); } else { image.dispose(); } }
如果圖片的大小小于此緩存的 [maximumSizeBytes],則使用此圖像更新最近最少使用的圖像緩存。
調整緩存大小以滿足 [maximumSize] 和 [maximumSizeBytes] 的約束。
// Remove images from the cache until both the length and bytes are below // maximum, or the cache is empty. void _checkCacheSize(TimelineTask? timelineTask) { final Map<String, dynamic> finishArgs = <String, dynamic>{}; TimelineTask? checkCacheTask; if (!kReleaseMode) { checkCacheTask = TimelineTask(parent: timelineTask)..start('checkCacheSize'); finishArgs['evictedKeys'] = <String>[]; finishArgs['currentSize'] = currentSize; finishArgs['currentSizeBytes'] = currentSizeBytes; } while (_currentSizeBytes > _maximumSizeBytes || _cache.length > _maximumSize) { final Object key = _cache.keys.first; final _CachedImage image = _cache[key]!; _currentSizeBytes -= image.sizeBytes!; image.dispose(); _cache.remove(key); if (!kReleaseMode) { (finishArgs['evictedKeys'] as List<String>).add(key.toString()); } } if (!kReleaseMode) { finishArgs['endSize'] = currentSize; finishArgs['endSizeBytes'] = currentSizeBytes; checkCacheTask!.finish(arguments: finishArgs); } assert(_currentSizeBytes >= 0); assert(_cache.length <= maximumSize); assert(_currentSizeBytes <= maximumSizeBytes); }
這段代碼實現了檢查緩存大小的邏輯,用于在緩存大小超過最大限制時從緩存中移除圖像以釋放內存。
該方法首先創建一個空的字典對象 finishArgs
用于保存一些統計數據,然后在非生產環境下創建一個時間線任務 checkCacheTask
,用于記錄緩存檢查的時間。如果檢查任務存在,則將 evictedKeys
、currentSize
和 currentSizeBytes
添加到 finishArgs
中。
然后,使用 while
循環,當緩存大小超過最大限制時,從 _cache
字典中刪除第一個元素,并釋放相關圖像的內存。如果 checkCacheTask
存在,則將已刪除的元素的鍵添加到 evictedKeys
列表中。
當循環結束時,將 endSize
和 endSizeBytes
添加到 finishArgs
中,表示緩存檢查后的當前大小和字節數。最后,如果 checkCacheTask
存在,則完成任務并將 finishArgs
作為參數傳遞。
最后,這個方法斷言 _currentSizeBytes
必須大于等于零, _cache
的長度必須小于等于 maximumSize
, _currentSizeBytes
必須小于等于 maximumSizeBytes
。
void _trackLiveImage(Object key, ImageStreamCompleter completer, int? sizeBytes) { // Avoid adding unnecessary callbacks to the completer. _liveImages.putIfAbsent(key, () { // Even if no callers to ImageProvider.resolve have listened to the stream, // the cache is listening to the stream and will remove itself once the // image completes to move it from pending to keepAlive. // Even if the cache size is 0, we still add this tracker, which will add // a keep alive handle to the stream. return _LiveImage( completer, () { _liveImages.remove(key); }, ); }).sizeBytes ??= sizeBytes; }
/// Returns the previously cached [ImageStream] for the given key, if available; /// if not, calls the given callback to obtain it first. In either case, the /// key is moved to the 'most recently used' position. /// /// The arguments must not be null. The `loader` cannot return null. /// /// In the event that the loader throws an exception, it will be caught only if /// `onError` is also provided. When an exception is caught resolving an image, /// no completers are cached and `null` is returned instead of a new /// completer. ImageStreamCompleter? putIfAbsent(Object key, ImageStreamCompleter Function() loader, { ImageErrorListener? onError }) { assert(key != null); assert(loader != null); TimelineTask? timelineTask; TimelineTask? listenerTask; if (!kReleaseMode) { timelineTask = TimelineTask()..start( 'ImageCache.putIfAbsent', arguments: <String, dynamic>{ 'key': key.toString(), }, ); } ImageStreamCompleter? result = _pendingImages[key]?.completer; // Nothing needs to be done because the image hasn't loaded yet. if (result != null) { if (!kReleaseMode) { timelineTask!.finish(arguments: <String, dynamic>{'result': 'pending'}); } return result; } // Remove the provider from the list so that we can move it to the // recently used position below. // Don't use _touch here, which would trigger a check on cache size that is // not needed since this is just moving an existing cache entry to the head. final _CachedImage? image = _cache.remove(key); if (image != null) { if (!kReleaseMode) { timelineTask!.finish(arguments: <String, dynamic>{'result': 'keepAlive'}); } // The image might have been keptAlive but had no listeners (so not live). // Make sure the cache starts tracking it as live again. _trackLiveImage( key, image.completer, image.sizeBytes, ); _cache[key] = image; return image.completer; } final _LiveImage? liveImage = _liveImages[key]; if (liveImage != null) { _touch( key, _CachedImage( liveImage.completer, sizeBytes: liveImage.sizeBytes, ), timelineTask, ); if (!kReleaseMode) { timelineTask!.finish(arguments: <String, dynamic>{'result': 'keepAlive'}); } return liveImage.completer; } try { result = loader(); _trackLiveImage(key, result, null); } catch (error, stackTrace) { if (!kReleaseMode) { timelineTask!.finish(arguments: <String, dynamic>{ 'result': 'error', 'error': error.toString(), 'stackTrace': stackTrace.toString(), }); } if (onError != null) { onError(error, stackTrace); return null; } else { rethrow; } } if (!kReleaseMode) { listenerTask = TimelineTask(parent: timelineTask)..start('listener'); } // A multi-frame provider may call the listener more than once. We need do make // sure that some cleanup works won't run multiple times, such as finishing the // tracing task or removing the listeners bool listenedOnce = false; // We shouldn't use the _pendingImages map if the cache is disabled, but we // will have to listen to the image at least once so we don't leak it in // the live image tracking. final bool trackPendingImage = maximumSize > 0 && maximumSizeBytes > 0; late _PendingImage pendingImage; void listener(ImageInfo? info, bool syncCall) { int? sizeBytes; if (info != null) { sizeBytes = info.sizeBytes; info.dispose(); } final _CachedImage image = _CachedImage( result!, sizeBytes: sizeBytes, ); _trackLiveImage(key, result, sizeBytes); // Only touch if the cache was enabled when resolve was initially called. if (trackPendingImage) { _touch(key, image, listenerTask); } else { image.dispose(); } _pendingImages.remove(key); if (!listenedOnce) { pendingImage.removeListener(); } if (!kReleaseMode && !listenedOnce) { listenerTask!.finish(arguments: <String, dynamic>{ 'syncCall': syncCall, 'sizeInBytes': sizeBytes, }); timelineTask!.finish(arguments: <String, dynamic>{ 'currentSizeBytes': currentSizeBytes, 'currentSize': currentSize, }); } listenedOnce = true; } final ImageStreamListener streamListener = ImageStreamListener(listener); pendingImage = _PendingImage(result, streamListener); if (trackPendingImage) { _pendingImages[key] = pendingImage; } // Listener is removed in [_PendingImage.removeListener]. result.addListener(streamListener); return result; }
這個是圖片緩存的核心方法。
(調用此方法不會減輕內存壓力,因為活動圖像緩存僅跟蹤同時由至少一個其他對象持有的圖像實例。)
/// Clears any live references to images in this cache. /// /// An image is considered live if its [ImageStreamCompleter] has never hit /// zero listeners after adding at least one listener. The /// [ImageStreamCompleter.addOnLastListenerRemovedCallback] is used to /// determine when this has happened. /// /// This is called after a hot reload to evict any stale references to image /// data for assets that have changed. Calling this method does not relieve /// memory pressure, since the live image caching only tracks image instances /// that are also being held by at least one other object. void clearLiveImages() { for (final _LiveImage image in _liveImages.values) { image.dispose(); } _liveImages.clear(); }
清除此緩存中任何圖像的現有引用。
如果一個圖像的 [ImageStreamCompleter] 至少添加了一個偵聽器并且從未達到零偵聽器,則認為該圖像是“現有的”。
[ImageStreamCompleter.addOnLastListenerRemovedCallback] 用于確定是否發生了這種情況。
在熱重載之后調用此方法以清除對已更改資產的圖像數據的任何過時引用。
調用此方法不會減輕內存壓力,因為活動圖像緩存僅跟蹤同時由至少一個其他對象持有的圖像實例。
_pendingImages 正在加載中的緩存,這個有什么作用呢? 假設Widget1加載了圖片A,Widget2也在這個時候加載了圖片A,那這時候Widget就復用了這個加載中的緩存
_cache 已經加載成功的圖片緩存
_liveImages 存活的圖片緩存,看代碼主要是在CacheImage之外再加一層緩存。收到內存警告時, 調用clear()方法清除緩存時, 并不是清除_liveImages, 因為官方解釋: 因為這樣做不會減少內存壓力。
感謝各位的閱讀,以上就是“Flutter加載圖片流程之ImageCache源碼分析”的內容了,經過本文的學習后,相信大家對Flutter加載圖片流程之ImageCache源碼分析這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。