Flutter 隐式动画

发布时间 2023-12-22 15:56:23作者: angelwgh

通过几行代码就可以实现隐式动画,由于隐式动画背后的实现原理和繁琐的操作细节都被隐去了,所以叫隐式动画,FLutter中提供的 [AnimatedContainer]、[AnimatedPadding]、[AnimatedPositioned.AnimatedOpacity]、[AnimatedDefaultTextStyle]、[AnimatedSwitcher]都属于隐式动画
隐式动画中可以通过 duration 配置动画时长、可以通过curve (曲线)来配置动画过程

import 'package:flutter/material.dart';

class MyAnimated extends StatelessWidget {
  const MyAnimated({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('动画'),
      ),
      body: AnimateContent(),
    );
  }
}

class AnimateContent extends StatefulWidget {
  const AnimateContent({super.key});

  @override
  State<AnimateContent> createState() => _AnimateContentState();
}

class _AnimateContentState extends State<AnimateContent> {
  late double width;
  late double height;
  Color color = Colors.indigoAccent;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    width = 200;
    height = 200;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          width: width,
          height: height,
          color: color,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            width = width == 100 ? 200 : 100;
            height = height == 100 ? 200 : 100;
            color = width == 100 ? Colors.indigoAccent : Colors.red;
          });
        },
        child: Icon(Icons.account_box_sharp),
      ),
    );
  }
}