美文网首页
Flutter-TweenAnimationBuilder实现隐

Flutter-TweenAnimationBuilder实现隐

作者: 阿博聊编程 | 来源:发表于2022-06-13 09:14 被阅读0次
配图来自网络,如侵必删

Flutter开发中,如果想要自定义隐式动画组件,但是不想通过自定义组件的方式实现的时候,我们可以通过TweenAnimationBuilder的方式来实现。这篇博客分享TweenAnimationBuilder相关的知识,希望对看文章的小伙伴有所启发。

TweenAnimationBuilder

我们使用TweenAnimationBuilder的时候,只需要向duration参数传入动画时长,向tween参数传入插值器对象,并在builder参数表示的函数中构造出使用动画的组件就可以了。源码如下所示:

const TweenAnimationBuilder({
    Key? key,
    required this.tween,
    required Duration duration,
    Curve curve = Curves.linear,
    required this.builder,
    VoidCallback? onEnd,
    this.child,
  }) : assert(tween != null),
       assert(curve != null),
       assert(builder != null),
       super(key: key, duration: duration, curve: curve, onEnd: onEnd);
}

实现旋转组件的动画

TweenAnimationBuilder<double>(
        tween: Tween<double>(begin: 0, end: angle),
        duration: const Duration(seconds: 2),
        builder: (BuildContext context, double angle, Widget? child) {
          return Transform.rotate(
            angle: angle,
            child: child,
          );
        },
        child: Image.asset('images/flutter.png'),
      )

上面的是使用代码。接下来是完整是示例代码,感兴趣的小伙伴可以直接复制到编译器上面运行,需要注意的是,我是直接拿文章的封面图做效果的,所以你需要将封面图片保存到项目的images文件当中:

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'TweenAnimationBuilder Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double angle = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: TweenAnimationBuilder<double>(
        tween: Tween<double>(begin: 0, end: angle),
        duration: const Duration(seconds: 2),
        builder: (BuildContext context, double angle, Widget? child) {
          return Transform.rotate(
            angle: angle,
            child: child,
          );
        },
        child: Image.asset('images/flutter.png'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 点击事件,设置动画开始
          setState(() {
            angle = 2 * 3.14;
          });
        },
        child: const Icon(Icons.play_arrow),
      ),
    );
  }
}

相关文章

网友评论

      本文标题:Flutter-TweenAnimationBuilder实现隐

      本文链接:https://www.haomeiwen.com/subject/goxomrtx.html