在水平ListView中对小部件进行动画处理

时间:2020-04-13 14:29:22

标签: flutter flutter-animation

考虑一个水平滚动的ListView,其中每个项目都是一个Stack。堆栈有两个小部件,底部是一个较大的蓝色容器,顶部是一个较小的琥珀色容器。当我点击蓝色的“容器”时,琥珀色的容器应在蓝色的容器外向右移动,将列表中的其余项目向右移动。我该怎么办?

ListView.builder(
  scrollDirection: Axis.horizontal,
  itemCount: 5,
  itemBuilder: (context, index) {
    return Padding(
            padding: EdgeInsets.only(right: 10.0),
            child: Stack(
              children: <Widget>[
                GestureDetector(
                  child: Container(
                    height: 120,
                    width: 90,
                    color: Colors.blue,
                  ),
                ),
                Container(
                  height: 90,
                  width: 30,
                  color: Colors.amber,
                )
              ],
            ),
          );
  },
),

屏幕截图:
Initial state, before the blue Container has been tapped
Final state, after the blue Container has been tapped

1 个答案:

答案 0 :(得分:1)

如果您要做的只是将内容滚动回到ListView的开头,那么以下代码将完成此操作:

class ScrollAnimation61190061 extends StatefulWidget {
  @override
  _ScrollAnimation61190061State createState() => _ScrollAnimation61190061State();
}

class _ScrollAnimation61190061State extends State<ScrollAnimation61190061> {
  final int _listLength = 5;
  List<EdgeInsets> _itemInsets = [];

  @override
  void initState() {
    _itemInsets = List.generate(_listLength, (index) => null);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: _listLength,
      itemBuilder: (context, index) {
        return Stack(
          children: <Widget>[
            GestureDetector(
              child: Container(
                height: 120,
                width: 90,
                color: Colors.blue,
              ),
              onTap: () {
                setState(() {
                  _itemInsets[index] = EdgeInsets.only(left: 60);
                });
              },
            ),
            Container(
              margin: _itemInsets[index],
              height: 90,
              width: 30,
              color: Colors.amber,
            )
          ],
        );
      },
    );
  }
}