推荐使用ListView.builder
来动态实现列表,而不是直接使用ListView
静态创建。注意这里在使用ListView.builder
的itemBuilder
来构建item时,可不要预构建Widget了。类似的Widget还有PageView.builder
和 GridView.builder
。
PS:按需加载是一种策略,并不是仅仅依靠这几个类型的Widget。比如之前阿里AliFlutter的分享中,就有提到列表中加载图片的优化。通过判断图片的在屏和离屏,来合理回收图片,这样减小了内存的波动,同样也可以带来性能的提升。
错峰加载
错峰加载的目的是为了避免因同一时间的大量构建,而产生卡顿现象。这里我举一个例子:
在使用PageView.builder
这个Widget时,我发现在左右滑动切换页面时会有卡顿的现象。使用timeline
来分析发现两个问题,一是切换的页面比较复杂,比较耗时。二是页面构建的时间点在滑动中。
页面复杂的问题我进行了一定的优化,虽然有效果,但还是有卡顿发生。那么只能针对第二点再进行优化,我们先看一下PageView.
相关源码:
return NotificationListener(
onNotification: (ScrollNotification notification) {
if (notification.depth == 0 && widget.onPageChanged != null && notification is ScrollUpdateNotification) {
final PageMetrics metrics = notification.metrics;
final int currentPage = metrics.page.round();
if (currentPage != _lastReportedPage) {
_lastReportedPage = currentPage;
widget.onPageChanged(currentPage);
}
}
return false;
},
child: Scrollable(),
);
代码很简单,如果我们设置了onPageChanged
的监听,那么在滑动中(ScrollUpdateNotification
)计算当前页的页码并返回(round方法,四舍五入)。所以在滑动到一半的时候,onPageChanged
就会回调结果,我因为在这里触发了页面的刷新代码,导致了卡顿的发生。
其实在我熟知的安卓中,默认行为都是在滑动结束后才去加载页面数据。所以按照这个思路处理,调整一下加载策略。
修改代码如下:
NotificationListener(
onNotification: (ScrollNotification notification) {
if (notification.depth == 0 && notification is ScrollEndNotification) {
final PageMetrics metrics = notification.metrics;
final int currentPage = metrics.page.round();
if (currentPage != _lastReportedPage) {
_lastReportedPage = currentPage;
_onPageChange(currentPage);
}
}
return false;
},
child: PageView.builder(),
)
我们在PageView.builder
上添加一个NotificationListener
,同时修改ScrollUpdateNotification
为ScrollEndNotification
。这样就自定义了我们的滑动监听事件,通过错峰加载保证了UI的流畅。
PS:在Flutter 1.17的重要改动中就有一条:[在高速滚动时推迟图像解码](()。这也是运用了错峰加载的策略。
5.耗时计算
避免将一些耗时计算放在UI线程,我们可以把耗时计算放到Isolate
去执行(多线程)。
举一个Flutter源码中的例子:
Future loadString(String key, { bool cache = true }) async {
final ByteData data = await load(key);
if (data == null)
throw FlutterError(‘Unable to load asset: k e y ′ ) ; i f ( d a t a . l e n g t h I n B y t e s < 10 ∗ 1024 ) / / 10 K B t a k e s a b o u t 3 m s t o p a r s e o n a P i x e l 2 X L . / / S e e : h t t p s : / / g i t h u b . c o m / d a r t − l a n