Flutter动画过渡插件tweener的使用

Flutter动画过渡插件tweener的使用

插件介绍

Tweener 是一个简单且轻量级的 Flutter 动画工具。任何人都可以轻松学习并使用它。

  • 功能
    • 只做一件事:平滑属性变化。
    • 非常简单易用,但可以实现很多效果。
    • 慢速函数可以在外部复用。

安装

安装 Tweener:

flutter packages get

在你的 Flutter 项目中添加以下依赖项:

dependencies:
  tweener: ^2.2.2

使用示例

导入类
import 'package:tweener/tweener.dart';
使用 Tweener
Tweener({"x": 0, "y": 0, "alpha": 0, "custom_prop_abc": 123})
    .to({"x": 100, "y": 500, "alpha": 1, "custom_prop_abc": 321}, 2000)
    .easing(Tweener.ease.elastic.easeOut)
    .onUpdate((obj) {
        setState(() {
            _x = obj["x"];
            _y = obj["y"];
            _alpha = obj["alpha"];
            _abc = obj["custom_prop_abc"];
        });
    })
    .onComplete((obj){
        /// 
    })
    .start();
复杂示例
var sprite = // 创建你的 Sprite 对象

var tween1 = new Tweener(sprite)
	.to({x: 700, y: 200, rotation: 359}, 2000)
	.delay(1000)
	.easing(Ease.back.easeOut)
	.onUpdate(update);

var tween2 = new Tweener(sprite)
	.to({x: 1, y: 20, rotation: 30}, 2000)
	.onUpdate(update);

tween1.chain(tween2);
tween1.start();

谢谢

Tweener 实现了 tween.js 的代码。 真的是很棒。 我想向 原作者致敬!


示例代码

import 'package:flutter/material.dart';
import 'package:tweener/tweener.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  // This widget is the home page of your application. It stateful, meaning
  // it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holdss the values
  // (in this case the title) provided by the parent (in this case the App widget)
  // and used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

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

  void _incrementCounter() {
    Tweener({"x": 0, "y": 0, "alpha": 0, "custom_prop_abc": 123})
        .to({"x": 100, "y": 500, "alpha": 1, "custom_prop_abc": 321}, 2000)
        .easing(Ease.elastic.easeOut)
        .onUpdate((obj) {
          setState(() {
            _counter = (obj["x"] * 100).round() * 1.0;
          });
        })
        .onComplete((obj) {
          ///
        })
        .start();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also layout widget. it takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.displayMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

更多关于Flutter动画过渡插件tweener的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter动画过渡插件tweener的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter中使用tweener插件进行动画过渡的一个示例。tweener插件允许你创建复杂而流畅的动画过渡效果。虽然tweener本身不是一个官方Flutter包,但假设你指的是一种常见的动画过渡处理方式,这里将展示如何使用Flutter内置的动画系统来实现类似的效果。

Flutter的动画系统非常强大,包括AnimationControllerTweenAnimatedWidget等核心组件。以下是一个简单的例子,展示如何使用这些组件来实现动画过渡:

1. 添加依赖

首先,确保你的pubspec.yaml文件中包含了必要的依赖项(虽然本例不依赖外部包,但通常动画可能需要flutter包本身):

dependencies:
  flutter:
    sdk: flutter

2. 创建动画控制器和Tween

在你的Flutter应用中,你需要一个AnimationController来控制动画的时间线,以及一个或多个Tween对象来定义动画的属性变化。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Tween Animation Example'),
        ),
        body: Center(
          child: MyAnimatedWidget(),
        ),
      ),
    );
  }
}

class MyAnimatedWidget extends StatefulWidget {
  @override
  _MyAnimatedWidgetState createState() => _MyAnimatedWidgetState();
}

class _MyAnimatedWidgetState extends State<MyAnimatedWidget> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat(reverse: true); // 动画会反复进行,且反向进行

    _animation = Tween<double>(begin: 0, end: 300).animate(_controller);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      child: Container(
        width: 100,
        height: 100,
        color: Colors.blue,
      ),
      builder: (context, child) {
        return Transform.translate(
          offset: Offset(_animation.value, 0),
          child: child,
        );
      },
    );
  }
}

3. 解释代码

  • AnimationController: 控制动画的时间线。在这个例子中,动画持续2秒,并且会反复进行。
  • Tween<double>: 定义动画的属性变化范围,从0到300。
  • AnimatedBuilder: 根据动画状态构建UI。在这里,它根据_animation的值来移动一个容器。
  • Transform.translate: 使用动画值来平移容器。

4. 运行应用

运行这个应用,你会看到一个蓝色的容器在屏幕上水平移动,动画会反复进行且反向进行。

这个例子展示了如何使用Flutter的内置动画系统来实现动画过渡效果。虽然tweener这个具体名称可能指向一个特定的库或功能,但Flutter的动画机制非常灵活,可以满足大多数动画需求。如果你确实在使用一个名为tweener的第三方库,请查阅该库的文档以获取更具体的用法示例。

回到顶部