Flutter 中的 ListView 的一个容易忽略的知识点

1,407 阅读3分钟

1. 前言

上一篇文章 Flutter渲染之通过demo了解Key的作用里面通过两个小 demo 讲了 Key 的作用。其实在写小 demo 的过程中也碰到一个问题,开始是没有想清楚的,后来跟同事交流,去源码里面翻了翻才找到一些原因,这里再来写一下。

2. 现象

在 demo2--交换两个小部件 开始提到,如果两个widget 是继承的 StatelessWidget,结果是可成功交换的,完整代码如下。

class KeyDemo1Page extends StatefulWidget {
  @override
  _KeyDemo1PageState createState() => _KeyDemo1PageState();
}

class _KeyDemo1PageState extends State<KeyDemo1Page> {

  List<Widget> tiles = [
    StatelessColorfulTile(),
    StatelessColorfulTile(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        centerTitle: true,
        title: Text("Key demo"),
      ),
      body: Column(children: tiles,),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.delete),
        onPressed: (){
          setState(() {
            tiles.insert(1, tiles.removeAt(0));
          });
        },
      ),
    );
  }
}

class StatelessColorfulTile extends StatelessWidget {
  Color myColor = Color.fromARGB(255, Random().nextInt(256), Random().nextInt(256), Random().nextInt(256));

  @override
  Widget build(BuildContext context) {
    print("build hahahahahha");
    return Container(
        color: myColor,
        child: Padding(padding: EdgeInsets.all(70.0))
    );
  }
}

如果将 body 里面的 Column 换为 ListView,tiles 赋值给 ListView 的 children,那么就不行了。点击按钮是没有切换的。这就很奇怪了,同样是容器啊,为啥一个可以一个不可以。为此我试了多种情况。

如果将点击按钮交换 tiles 数组元素改为删除一个元素,界面也还是没有反应; 如果将交换元素改为新创建一个数组,将 tiles 元素插入到新数组里面,然后让tiles 指向新数组,这样结果就是好的。

也就是说改变 tiles 数组里面元素的位置或者增减元素界面都不会有反应,只有改变 tiles 指向界面才可以切换。

将 ListView(children:tiles) 改为 ListView.builder 的形式是可以的,如下代码。

class _KeyDemo1PageState extends State<KeyDemo1Page> {
  ......

  Widget _itemForRow(BuildContext context, int index) {
    return tiles[index];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      ......
      body: ListView.builder(
        itemCount: tiles.length,
        itemBuilder: _itemForRow,
      ),
      ......
    );
  }
}

3. 原因

使用 ListView 和 ListView.builder 是有区别的,因此可以对比着去源码里面看看。

ListView 的构造方法如下

istView({
    Key key,
    Axis scrollDirection = Axis.vertical,
    bool reverse = false,
    ScrollController controller,
    bool primary,
    ScrollPhysics physics,
    bool shrinkWrap = false,
    EdgeInsetsGeometry padding,
    this.itemExtent,
    bool addAutomaticKeepAlives = true,
    bool addRepaintBoundaries = true,
    bool addSemanticIndexes = true,
    double cacheExtent,
    List<Widget> children = const <Widget>[],
    int semanticChildCount,
    DragStartBehavior dragStartBehavior = DragStartBehavior.start,
  }) : childrenDelegate = SliverChildListDelegate(
         children,
         addAutomaticKeepAlives: addAutomaticKeepAlives,
         addRepaintBoundaries: addRepaintBoundaries,
         addSemanticIndexes: addSemanticIndexes,
       ),
       super(
         key: key,
         scrollDirection: scrollDirection,
         reverse: reverse,
         controller: controller,
         primary: primary,
         physics: physics,
         shrinkWrap: shrinkWrap,
         padding: padding,
         cacheExtent: cacheExtent,
         semanticChildCount: semanticChildCount ?? children.length,
         dragStartBehavior: dragStartBehavior,
       );

children 也赋值到 SliverChildListDelegate 里面去了,因此也去它里面看看,在 SliverChildListDelegate 里面发现了一个重要的方法,如下

@override
  bool shouldRebuild(covariant SliverChildListDelegate oldDelegate) {
    return children != oldDelegate.children;
  }

发现了,如果 ListView 的孩子数组没有改变的话 shouldRebuild 就会返回 false,也就不会执行 build 方法了,因此界面也不会有什么变化。可以想象 ListView.builder 里面也有这种方法,不过返回结果应该不一样,去看看吧。

ListView.builder 的构造函数这样的

ListView.builder({
    Key key,
    Axis scrollDirection = Axis.vertical,
    bool reverse = false,
    ScrollController controller,
    bool primary,
    ScrollPhysics physics,
    bool shrinkWrap = false,
    EdgeInsetsGeometry padding,
    this.itemExtent,
    @required IndexedWidgetBuilder itemBuilder,
    int itemCount,
    bool addAutomaticKeepAlives = true,
    bool addRepaintBoundaries = true,
    bool addSemanticIndexes = true,
    double cacheExtent,
    int semanticChildCount,
    DragStartBehavior dragStartBehavior = DragStartBehavior.start,
  }) : assert(itemCount == null || itemCount >= 0),
       assert(semanticChildCount == null || semanticChildCount <= itemCount),
       childrenDelegate = SliverChildBuilderDelegate(
         itemBuilder,
         childCount: itemCount,
         addAutomaticKeepAlives: addAutomaticKeepAlives,
         addRepaintBoundaries: addRepaintBoundaries,
         addSemanticIndexes: addSemanticIndexes,
       ),
       super(
         key: key,
         scrollDirection: scrollDirection,
         reverse: reverse,
         controller: controller,
         primary: primary,
         physics: physics,
         shrinkWrap: shrinkWrap,
         padding: padding,
         cacheExtent: cacheExtent,
         semanticChildCount: semanticChildCount ?? itemCount,
         dragStartBehavior: dragStartBehavior,
       );

我们去 SliverChildBuilderDelegate 里面看看,发现也有一个 shouldRebuild 方法,代码如下。

@override
  bool shouldRebuild(covariant SliverChildBuilderDelegate oldDelegate) => true;

因此可以看出使用 ListView.builder 的话 shouldRebuild 默认返回 true,因此这种方法build 都会执行,所以界面是可以切换的。

4. 总结

执行 setState 的后,ListView 的 children 里面的元素改变,包括移动和增删,界面是不会改变的,只能是改变整个 children 指向。使用 ListView.builder 则会改变。

从开始发现问题到尝试了各种现象发现一些基本规律,然后去源码里面找原因,基本可以搞清楚问题所在,不过还是有一些技术细节需要更深入一层理解了。