如何从页面视图中删除具有平滑动画的页面?

时间:2019-02-27 16:43:36

标签: flutter flutter-layout flutter-animation

我还是不太熟悉动画,并且我试图使PageView随动画一起按下时消失。

我有此代码:

moveExisting

上述代码的作者:https://stackoverflow.com/a/47357960/1194779

产生以下内容: enter image description here

现在,我需要在按下卡片上的动画时将其关闭。

我尝试过实现SlideTransition来向下滑动卡。但是我无法使PageView动画化刚刚移除的卡片的填充空白空间。

1 个答案:

答案 0 :(得分:0)

您可以使用 Dismissible 在您的小部件上启用滑动手势。尽管与 PageViews 一起使用时,Dismissible 会产生可能不受欢迎的卡顿。

class Carousel extends StatefulWidget {
  @override
  _CarouselState createState() => _CarouselState();
}

class _CarouselState extends State<Carousel>{
  late PageController controller;
  int currentPage = 0;
  List<String> listItem = ['Page 1', 'Page 2', 'Page 3', 'Page 4'];

  @override
  initState() {
    super.initState();
    controller = PageController(
      initialPage: currentPage,
      keepPage: false,
      viewportFraction: 0.5,
    );
  }

  @override
  dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          child: PageView.builder(
            itemCount: listItem.length,
            onPageChanged: (value) {
              setState(() {
                currentPage = value;
              });
            },
            controller: controller,
            itemBuilder: (BuildContext context, int index) =>
                pageBuilder(index),
          ),
        ),
      ),
    );
  }

  pageBuilder(int index) {
    var dismissibleKey = GlobalKey<State>();
    return AnimatedBuilder(
      animation: controller,
      builder: (context, child) {
        double value = 1.0;
        if (controller.position.haveDimensions) {
          value = controller.page! - index;
          value = (1 - (value.abs() * .5)).clamp(0.0, 1.0);
        }

        return Center(
          child: SizedBox(
            height: Curves.easeOut.transform(value) * 300,
            width: Curves.easeOut.transform(value) * 250,
            child: child,
          ),
        );
      },
      child: Dismissible(
        key: dismissibleKey,
        direction: DismissDirection.down,
        onDismissed: (DismissDirection direction) {
          /// Remove item from List
          setState(() {
            listItem.removeAt(index);
          });
        },
        child: InkWell(
          onLongPress: () {
            debugPrint('Delete! $index');
            setState(() {
              listItem.removeAt(index);
            });
          },
          onTap: () {
            controller.animateToPage(index,
                duration: Duration(milliseconds: 500), curve: Curves.ease);
          },
          child: Container(
            margin: const EdgeInsets.all(8.0),
            // color: index % 2 == 0 ? Colors.blue : Colors.red,
            color: Colors.lightBlueAccent,
            child: Center(
              child: Text('${listItem[index]}'),
            ),
          ),
        ),
      ),
    );
  }
}

Demo