使用AnimatedSwitcher和Dismissible进行页面滑动的行为

时间:2020-07-07 06:45:12

标签: flutter flutter-animation

我正在尝试实现$ subject。当我向左侧滑动时(运动向右->左侧),动画会正确发生,并且小部件从右侧开始并停留。但是,当我向右侧滑动时,会发生小部件转换,但是小部件开始从右侧而不是左侧出现。

我正在尝试像平常一样在日历中滑动。

enter image description here

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MainPage(),
    );
  }
}

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  Widget child;

  @override
  void initState() {
    super.initState();
    child = Container(
      child: Center(
        child: Text(
          'Main',
          style: TextStyle(fontSize: 18.0),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: AnimatedSwitcher(
        duration: const Duration(milliseconds: 350),
        switchInCurve: Curves.easeIn,
        switchOutCurve: Curves.easeOut,
        transitionBuilder: (child, animation) {
          return SlideTransition(
            position: Tween<Offset>(begin: Offset(1.2, 0), end: Offset(0, 0))
                .animate(animation),
            child: child,
          );
        },
        layoutBuilder: (currentChild, _) => currentChild,
        child: Dismissible(
          key: UniqueKey(),
          resizeDuration: null,
          onDismissed: _onHorizontalSwipe,
          direction: DismissDirection.horizontal,
          child: child,
        ),
      ),
    );
  }

  void _onHorizontalSwipe(DismissDirection direction) {
    if (direction == DismissDirection.startToEnd) {
      setState(() {
        child = Page1();
      });
    } else {
      setState(() {
        child = Page2();
      });
    }
  }
}

class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.yellow,
      child: Center(
        child: Text(
          'Left side page',
          style: TextStyle(fontSize: 18.0),
        ),
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blueAccent,
      child: Center(
        child: Text(
          'Right side page',
          style: TextStyle(fontSize: 18.0),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您可能已经知道了,但是,transitionbuilder 中的动画值将始终从 0 运行到 1,因此您始终会获得相同的过渡。您必须设置向左或向右滑动条件。