首页 > 建站教程 > APP开发,混合APP >  Flutter笔记68:Flutter动画基础正文

Flutter笔记68:Flutter动画基础

Flutter动画相关类:
  Animation:Flutter中动画的核心类,是个抽象类(abstract),通过Listeners和StatusListeners可以进行监听。
  AnimationController:动画管理类,AnimationController继承自Animation,是特殊的Animation类。
  CurvedAnimation:用于定义非线性曲线动画,继承自Animation,属于Animation<double>类型
  Tween:补间对象,用于计算动画使用的数据范围之间的插值
  Listeners和StatusListeners:用于监听动画状态改变

字体放大案例:
main.dart:
import 'package:flutter/material.dart';
import './font.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: MaterialApp(
        title: 'Flutter动画',
        theme: ThemeData(
          primarySwatch: Colors.blue
        ),
        debugShowCheckedModeBanner: false,
        home: AnimateDemo(),
      ),
    );
  }
}

class AnimateDemo extends StatelessWidget{
  @override
  Widget build(BuildContext context) {

    List<Widget> list = [
      FontAnimation()
    ];

    return Scaffold(
      appBar: AppBar(
        title: Text('动画示例'),
      ),
      body: ListView(
        children: list.map((widget){
          return ListTile(
            title: Text(widget.toString()),
            onTap: (){
              Navigator.of(context).push(MaterialPageRoute(builder: (context)=>widget));
            },
          );
        }).toList(),
      ),
    );
  }
}
font.dart:
import 'package:flutter/material.dart';

class FontAnimation extends StatefulWidget{
  FontAnimation({Key key}) : super(key:key);

  _FontAnimationState createState() => _FontAnimationState();
}

//混入 SingleTickerProviderStateMixin 是为了在不显示当前页面时,动画停止,节约资源
class _FontAnimationState extends State<FontAnimation> with SingleTickerProviderStateMixin{
  Animation<double> tween;
  AnimationController controller;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(duration:Duration(milliseconds: 2000), vsync: this);
    tween = Tween(begin: 0.0, end: 1.0).animate(controller)..addListener(() {
      setState(() {
        print(tween);
      });
    });
    //执行动画
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter动画'),
      ),
      body: GestureDetector(
        onTap: (){
          startAnimation();
        },
        child: Center(
          child: Text(
            '字体放大',
            style: TextStyle(
              fontSize: 60 * controller.value
            ),
          ),
        ),
      ),
    );
  }

  startAnimation(){
    setState(() {
      controller.forward(from: 0.0);
    });
  }

}