Flutter动画注释插件animated_vector_annotations的使用

发布于 1周前 作者 nodeper 来自 Flutter

Flutter动画注释插件animated_vector_annotations的使用

animated_vector_annotations 包包含用于与 animated_vectoranimated_vector_gen 一起使用的注解。

更多详细信息请参阅 animated_vector_gen 文档。

示例代码

下面是一个简单的示例,演示如何在 Flutter 中使用 animated_vector_annotations 插件。

步骤 1: 添加依赖

首先,在 pubspec.yaml 文件中添加 animated_vectoranimated_vector_gen 的依赖:

dependencies:
  flutter:
    sdk: flutter
  animated_vector: ^0.1.0
  animated_vector_gen: ^0.1.0

然后运行 flutter pub get 来安装这些依赖。

步骤 2: 创建动画矢量文件

创建一个 SVG 文件,例如 example.svg。SVG 文件定义了动画的基本形状和路径。

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <path id="heart" d="M80 20 C 80 20, 40 80, 20 80 C 20 80, 60 20, 80 20 Z"/>
</svg>

步骤 3: 生成注解代码

使用 animated_vector_gen 工具生成注解代码。此工具将 SVG 文件转换为 Dart 代码。

flutter packages pub run animated_vector_gen example.svg

这将在你的项目中生成一个 Dart 文件,例如 example.g.dart

步骤 4: 在 Flutter 项目中使用动画矢量

在你的 Flutter 项目中使用生成的 Dart 文件。以下是一个完整的示例:

import 'package:flutter/material.dart';
import 'package:animated_vector/animated_vector.dart';
import 'example.g.dart'; // 引入生成的 Dart 文件

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Animated Vector Example')),
        body: Center(
          child: AnimatedVectorWidget(
            animation: ExampleAnimation(), // 使用生成的动画类
            child: SvgPicture.string(ExampleSvg.example), // 使用生成的 SVG 图片
          ),
        ),
      ),
    );
  }
}

步骤 5: 运行应用

运行你的 Flutter 应用,你应该能看到使用 animated_vector_annotations 插件创建的动画效果。

flutter run

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

1 回复

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


当然,以下是如何在Flutter项目中使用animated_vector_annotations插件来实现动画注释的示例代码。这个插件主要用于为AnimatedVectorDrawable提供注释,使得动画过程更加清晰易懂。不过需要注意的是,animated_vector_annotations本身是一个辅助工具,主要和animated_vector_drawable结合使用,而Flutter本身并不直接支持AnimatedVectorDrawable(这是Android特有的概念)。为了在Flutter中达到类似效果,我们通常使用Flutter的动画系统。

不过,为了展示如何使用animated_vector_annotations(假设你在一个包含原生Android代码支持的Flutter项目中),我们可以模拟一个场景,其中我们创建一个简单的Android原生动画,并在其中添加注释。然后,我们将这个动画通过平台通道在Flutter中展示。

步骤 1: 在Android原生部分创建动画

首先,在android/app/src/main/res/drawable目录下创建一个avd文件(animated_vector_drawable),比如example_animation.xml

<!-- example_animation.xml -->
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/ic_example">

    <target
        android:name="heart"
        android:animation="@animator/heart_pulse"/>

    <!-- 这里可以添加 animated_vector_annotations 的注释,但注意,实际注释是在代码中添加的,不是XML -->
</animated-vector>

然后,创建一个动画资源文件,比如heart_pulse.xml,在android/app/src/main/res/animator目录下:

<!-- heart_pulse.xml -->
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:duration="600"
        android:propertyName="scaleX"
        android:valueFrom="1.0"
        android:valueTo="1.2"
        android:repeatCount="infinite"
        android:repeatMode="reverse"/>
    <objectAnimator
        android:duration="600"
        android:propertyName="scaleY"
        android:valueFrom="1.0"
        android:valueTo="1.2"
        android:repeatCount="infinite"
        android:repeatMode="reverse"/>
</set>

步骤 2: 在Android代码中使用动画并添加注释

虽然animated_vector_annotations本身不提供XML注释功能,但你可以通过代码注释来解释动画逻辑。例如,在Activity中加载动画:

// MainActivity.java
package com.example.flutterapp;

import android.graphics.drawable.AnimatedVectorDrawable;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageView = findViewById(R.id.imageView);
        AnimatedVectorDrawable avd = (AnimatedVectorDrawable) ContextCompat.getDrawable(this, R.drawable.example_animation);
        imageView.setImageDrawable(avd);
        avd.start();

        // 动画注释
        // 这个动画使心形图标以1.2倍的尺寸脉冲式放大缩小,无限循环
    }
}

步骤 3: 在Flutter中调用原生动画

为了在Flutter中展示这个动画,你需要使用平台通道。这里是一个简单的示例,展示如何通过MethodChannel从Flutter调用Android原生代码来启动动画。

首先,在Flutter中设置MethodChannel

// main.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

class MyApp extends StatelessWidget {
  static const platform = MethodChannel('com.example.flutterapp/channel');

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter AnimatedVectorDrawable Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              try {
                await platform.invokeMethod('startAnimation');
              } on PlatformException catch (e) {
                print("Failed to invoke: '${e.message}'.");
              }
            },
            child: Text('Start Animation'),
          ),
        ),
      ),
    );
  }
}

然后,在Android原生代码中处理平台通道请求:

// MainActivity.java (续)
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "com.example.flutterapp/channel";

    @Override
    public void configureFlutterEngine(FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler(
                        (call, result) -> {
                            if (call.method.equals("startAnimation")) {
                                ImageView imageView = findViewById(R.id.imageView);
                                AnimatedVectorDrawable avd = (AnimatedVectorDrawable) imageView.getDrawable();
                                if (avd != null && !avd.isRunning()) {
                                    avd.start();
                                }
                                result.success(null);
                            } else {
                                result.notImplemented();
                            }
                        }
                );
    }
}

这个示例展示了如何在Flutter项目中结合使用Android原生动画和平台通道。虽然animated_vector_annotations插件主要用于Android Studio环境,通过代码注释来解释动画逻辑,但通过上述方法,你可以在Flutter应用中集成并利用这些动画。

回到顶部