Flutter:小部件在动画之间切换

时间:2020-09-28 17:20:35

标签: flutter dart

我试图为小部件切换位置制作动画。下图显示了A和B小部件,单击按钮后,我想在A到B / B到A之间切换。但是起初我不知道从哪里开始,我不知道有什么插件可以实现,任何建议都可以帮助我,只是一些技巧,我愿意研究建议插件。

enter image description here

我尝试使用AnimatedAlign

Container(
height: 120.0,
color: Colors.black,
child: Column(
  children: [
    AnimatedAlign(
      alignment: _alignment.value = _alignment.value == Alignment.topCenter ? Alignment.bottomCenter : _alignment.value,
      curve: Curves.ease,
      duration: Duration(milliseconds: 500),
      child: Padding(
        padding: EdgeInsets.all(2.5),
          child: Container(
          height: 55,
          color: Colors.red,
        ),
      )
    ),
    AnimatedAlign(
      alignment: _alignment.value = _alignment.value == Alignment.bottomCenter ? Alignment.topCenter : _alignment.value,
      curve: Curves.ease,
      duration: Duration(milliseconds: 500),
      child: Padding(
        padding: EdgeInsets.all(2.5),
          child: Container(
          height: 55,
          color: Colors.blue,
        ),
      ),
    )
  ],
),
),
RaisedButton(
onPressed: () {
  _alignment.value = Alignment.bottomCenter;
},
child: Text("Switch Position"),
)

1 个答案:

答案 0 :(得分:1)

我创建了一个示例...正在运行。我使用了动画定位

import 'package:flutter/material.dart';

void main() {
  runApp(MyClass());
}

class MyClass extends StatefulWidget {
  @override
  _MyClassState createState() => _MyClassState();
}

class _MyClassState extends State<MyClass>{

  bool change = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(title: Text('Title')),
        body: Stack(
          children: <Widget>[
            AnimatedPositioned(
              top: change ?  50 : 150,
              left: 50,
              right: 50,
              duration: Duration(milliseconds: 300),
              child: red()
            ),
            AnimatedPositioned(
                top: change ?  150 : 50,
                left: 50,
                right: 50,
              duration: Duration(milliseconds: 300),
              child: blue()
            ),
            Positioned(
              top: 210,
              left: 50,
              right: 50,
              child: Center(
                child: InkWell(
                  onTap: (){
                    setState(() {
                      change = !change;
                    });
                  },
                  child: Container(
                    color: Colors.amber,
                    width: 65,
                    height: 50,
                    child: Center(child: Text("click me")),
                  ),
                ),
              ),
            )
          ],
        ),
        ),
    );
  }
}

red(){
  return Container(
    width: 120,
    height: 50,
    color: Colors.red,
  );
}
blue(){
  return Container(
    width: 120,
    height: 50,
    color: Colors.blue,
  );
}