2分钟教你Flutter怎么避免引用内存泄漏
内存泄漏原因
所有语言的内存泄漏无非就是GC Root(线程,全局或静态数组或引用等)的引用链持有了需要释放的引用,导致无法释放。
解决释放的方法,无非就是2种,如下:
1. 在当前类,或者方法等移除改引用,让其他自动释放,等下一轮GC扫描释放。如
class B{
void doSomething(){
}
}
class A{
B? b;
}
A a = A();
void test(){
a.b = B();
a.b?.doSomething();
}
void dispose(){
a.b = null;
}
void main() {
test();
dispose();
}
A 这时候时全局的,如果使用完B后,想要B自动释放,只需要调用dispose() 将B置null就好。
然后,现实就是有可能,忘记调用dispose().导致B无法释放。怎么办呢?对,你猜到了,就是弱引用,Dart也有!
来了来了就是那个闪亮的仔, WeakReference(和Java的弱引用名字一样哦)
2. 使用弱引用-----WeakReference,当前使用完,生命周期结束后,自动释放。
在上面代码,B的生命周期,仅仅是在test这个方法里面,所以执行test后B就不需要用了,那么就让他自动等GC移除.
让我们看看他的源码
/// A weak reference to a Dart object.
///
/// A _weak_ reference to the [target] object which may be cleared
/// (set to reference `null` instead) at any time
/// when there is no other way for the program to access the target object.
///
/// _Being the target of a weak reference does not keep an object
/// from being garbage collected._
///
/// There are no guarantees that a weak reference will ever be cleared
/// even if all references to its target are weak references.
///
/// Not all objects are supported as targets for weak references.
/// The [WeakReference] constructor will reject any object that is not
/// supported as an [Expando] key.
///
/// Use-cases like caching can benefit from using weak references. Example:
///
/// ```dart
/// /// [CachedComputation] caches the computation result, weakly holding
/// /// on to the cache.
/// ///
/// /// If nothing else in the program is holding on the result, and the
/// /// garbage collector runs, the cache is purged, freeing the memory.
/// ///
/// /// Until the cache is purged, the computation will not run again on
/// /// a subsequent request.
/// ///
/// /// Example use:
/// /// ```
/// /// final cached = CachedComputation(
/// /// () => jsonDecode(someJsonSource) as Object);
/// /// pri