Animating position across row cells in Flutter

我的未来我决定 提交于 2021-02-11 15:31:35

问题


I have a Row Widget that holds a child Widget in one of its cells (the others hold a Spacer()). Depending on the state, the cell which holds the child changes, resulting in a position change of the child Widget. I want to animate this motion to make it smooth. Is there a way of doing so with the standard animation Widgets (something like AnimatedPositioned, which won't work in this case)?


回答1:


You could use AnimatedPositioned if you insert a Stack inside your row. Otherwise, you can use an AnimatedBuilder with Transform.translate and animate the Offset on the axis X of your widget. Bellow there's a complete example, that you can run at DartPad to see the result. Hope it helps.

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),]
        );
      },
    ),
  );
}
  
  
  
}


来源:https://stackoverflow.com/questions/62602183/animating-position-across-row-cells-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!