首页 > 解决方案 > Flutter中跨行单元格的动画位置

问题描述

我有一个Row小部件,它在它的一个单元格中保存一个子小部件(其他的有一个Spacer())。根据状态的不同,持有孩子的单元格会发生变化,从而导致孩子 Widget 的位置发生变化。我想为这个动作制作动画以使其平滑。有没有办法使用标准动画小部件(类似AnimatedPositioned,在这种情况下不起作用)?

标签: flutteranimation

解决方案


如果在行内插入 Stack,则可以使用 AnimatedPositioned。否则,您可以在小部件的 X 轴上使用AnimatedBuilderwithTransform.translate并为其设置动画。Offset下面有一个完整的示例,您可以在DartPad上运行以查看结果。希望能帮助到你。

import 'package:flutter/material.dart';

void main(){
  
  runApp(MaterialApp(home: MyAnimation()));

}

class MyAnimation extends StatefulWidget {
@override
_MyAnimationState createState() => _MyAnimationState();
}

class _MyAnimationState extends State<MyAnimation> with SingleTickerProviderStateMixin {

  
  AnimationController _controller;
  Animation<double> animation;

@override
void initState() {
  super.initState();
  _controller = AnimationController(vsync: this, duration: Duration(milliseconds: 5000));
  animation = Tween(begin: 0.0, end: 300.0).animate(_controller);
  _controller.forward();
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: Text("Title")),
    body: AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Row(
          children: <Widget>[ 
            Transform.translate(
            child: Container(width: 100, height: 100, color: Colors.black),
            offset: Offset(animation.value, 0),
          ),
          Container(width: 100, height: 100, color: Colors.transparent),
          Container(width: 100, height: 100, color: Colors.transparent),]
        );
      },
    ),
  );
}
  
  
  
}

推荐阅读