前言
在原生android和ios上关于列表的组件默认都会支持复用和懒加载来提升性能和用户体验,在flutter中也不例外。flutter中提供的常用的列表组件例如ListView、GridView等也都支持复用和懒加载。在正常使用或者说不复杂的布局中,我们不需要去关心这些列表组件是否正常使用了复用和懒加载,但是在复杂(多种嵌套)或有大量数据交互的界面中,如果列表没有使用复用和懒加载那么带来的性能问题将是一个灾难。
懒加载测试
简单布局中测试
首先我们来看看简单布局下flutter中列表懒加载的表现:
import 'package:flutter/material.dart';
class ListPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return ListPageState();
}
}
class ListPageState extends State<ListPage> {
int count = 60;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: InkWell(
child: Text('List Test'),
onTap: () {},
),
),
body: ListView.builder(
itemBuilder: (context, index) {
print('this is index = $index');
return Container(
height: 100,
decoration: BoxDecoration(border: Border.all(color: Colors.purple, width: 1)),
child: Center(child: Text('$index')),
);
},
itemCount: 60,
),
);
}
}
在我们刚打开页面时,一共只加载了8个布局,而页面上我们能看见的只有5个,这个是因为列表会预加载超