Flutter中的同时多部件动画

l2osamch  于 2023-05-23  发布在  Flutter
关注(0)|答案(1)|浏览(180)

要求

在我的Flutter应用程序中,我有3个文本小部件,其中包含文本“one”,“two”和“three”。我想一次显示一个,动画应该如下所示:

  • “one”从右侧(Offset(1,0))滑动到中心(Offset.zero)并在那里停留1秒
  • 然后它从中心(Offset.zero)向左(Offset(-1,0))滑动,而“two”以与“one”相同的方式从右向中心滑动。
  • “二”在那里停留另外1秒,并且我们重复地继续此。
  • 动画可以在页面顶部查看here。*
    我尝试的内容:

我尝试使用AnimatedSwitcher来实现它,如下所示,但它给出了意想不到的结果。

AnimatedSwitcher(
      duration: const Duration(milliseconds: 1000),
      reverseDuration: Duration(seconds: 0),
      transitionBuilder: (Widget child, Animation<double> animation) {
        return SlideTransition(
          position: Tween<Offset>(
            begin: Offset(3.0, 0.0),
            end: Offset(1, 0),
          ).animate(animation),
          child: child,
        );
      },
      child: SlideTransition(
        key: Key(texts[currentIdx]),
        position: Tween<Offset>(
          begin: Offset.zero,
          end: Offset(-3.0, 0.0),
        ).animate(_controller),
        child: Text(
          texts[currentIdx],
          style: TextStyle(fontSize: 30),
        ),
      ),
    );

我怎样才能实现这个动画?

bhmjp9jg

bhmjp9jg1#

@pskink让我意识到我在看一个完全错误的方向。我用pageView. builder解决了这个问题。代码如下:

class _WordSliderState extends State<WordSlider> {
  List<String> texts = ["one", "two", "three"];
  late PageController _contoller;

  @override
  void initState() {
    super.initState();
    _contoller = PageController(
      keepPage: true,
    );
    Timer timer = Timer.periodic(Duration(seconds: 2), (_) {
      setState(() {
        _contoller.nextPage(
          curve: Curves.ease,
          duration: const Duration(seconds: 1),
        );
      
      });
    });
  }

  @override
  void dispose() {
    _contoller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        height: 60,
        width: 120,
        child: PageView.builder(
          controller: _contoller,
          itemBuilder: (context, index) {
            return Text(
              texts[index % 3],
              style: TextStyle(
                fontFamily: "DM_Sans",
                fontSize: 35,
              ),
            );
          },
        ));
  }
}

相关问题