Flutter-animation

提供:Dev Guides
移動先:案内検索

フラッター-アニメーション

アニメーションは、モバイルアプリケーションでは複雑な手順です。 複雑さにもかかわらず、Animationはユーザーエクスペリエンスを新しいレベルに高め、リッチなユーザーインタラクションを提供します。 その豊富さにより、アニメーションは現代のモバイルアプリケーションの不可欠な部分になります。 Flutterフレームワークは、アニメーションの重要性を認識し、あらゆる種類のアニメーションを開発するためのシンプルで直感的なフレームワークを提供します。

前書き

アニメーションは、特定の時間内に特定の順序で一連の画像/画像を表示して、動きの錯覚を与えるプロセスです。 アニメーションの最も重要な側面は次のとおりです-

  • アニメーションには、開始値と終了値の2つの異なる値があります。 アニメーションは_Start_値から始まり、一連の中間値を通過し、最終的に終了値で終了します。 たとえば、ウィジェットをアニメーション化してフェードアウトさせる場合、初期値は完全な不透明度になり、最終値は不透明度ゼロになります。
  • 中間値は、本質的に線形または非線形(曲線)であり、構成できます。 アニメーションは設定どおりに機能することを理解してください。 各構成は、アニメーションに異なる感触を提供します。 たとえば、ウィジェットのフェードは本質的に線形になりますが、ボールの跳ね返りは本質的に非線形になります。
  • アニメーションプロセスの継続時間は、アニメーションの速度(低速または高速)に影響します。
  • アニメーションの開始、アニメーションの停止、アニメーションの繰り返し回数の設定、アニメーションのプロセスの反転など、アニメーションプロセスを制御する機能。
  • Flutterでは、アニメーションシステムは実際のアニメーションを行いません。 代わりに、画像をレンダリングするためにすべてのフレームで必要な値のみを提供します。

アニメーションベースのクラス

フラッターアニメーションシステムは、アニメーションオブジェクトに基づいています。 コアアニメーションクラスとその使用法は次のとおりです-

アニメーション

特定の期間にわたって2つの数値の間に補間値を生成します。 最も一般的なアニメーションのクラスは-

  • Animation <double> -2つの10進数の間の値を補間します
  • Animation <Color> -2つの色の間の色を補間する
  • Animation <Size> -2つのサイズの間のサイズを補間します
  • AnimationController -アニメーション自体を制御する特別なアニメーションオブジェクト。 アプリケーションが新しいフレームの準備ができるたびに新しい値を生成します。 リニアベースのアニメーションをサポートし、値は0.0から1.0で始まります
controller = AnimationController(duration: const Duration(seconds: 2), vsync: this);

ここで、コントローラーはアニメーションを制御し、持続時間オプションはアニメーションプロセスの持続時間を制御します。 vsyncは、アニメーションで使用されるリソースを最適化するために使用される特別なオプションです。

曲線アニメーション

AnimationControllerに似ていますが、非線形アニメーションをサポートしています。 CurvedAnimationは、以下のようにAnimationオブジェクトとともに使用できます-

controller = AnimationController(duration: const Duration(seconds: 2), vsync: this);
animation = CurvedAnimation(parent: controller, curve: Curves.easeIn)

トゥイーン<T>

Animatable <T>から派生し、0と1以外の2つの数値の間の数値を生成するために使用されます。 animateメソッドを使用して実際のAnimationオブジェクトを渡すことにより、Animationオブジェクトと共に使用できます。

AnimationController controller = AnimationController(
   duration: const Duration(milliseconds: 1000),
vsync: this); Animation<int> customTween = IntTween(
   begin: 0, end: 255).animate(controller);
  • Tweenは、以下のようにCurvedAnimationとともに使用することもできます-
AnimationController controller = AnimationController(
   duration: const Duration(milliseconds: 500), vsync: this);
final Animation curve = CurvedAnimation(parent: controller, curve: Curves.easeOut);
Animation<int> customTween = IntTween(begin: 0, end: 255).animate(curve);

ここで、コントローラーは実際のアニメーションコントローラーです。 curveは非線形性のタイプを提供し、customTweenは0〜255のカスタム範囲を提供します。

Flutter Animationのワークフロー

アニメーションのワークフローは次のとおりです-

  • StatefulWidgetのinitStateでアニメーションコントローラーを定義して開始します。
AnimationController(duration: const Duration(seconds: 2), vsync: this);
animation = Tween<double>(begin: 0, end: 300).animate(controller);
controller.forward();
  • アニメーションベースのリスナー、addListenerを追加して、ウィジェットの状態を変更します。
animation = Tween<double>(begin: 0, end: 300).animate(controller) ..addListener(() {
   setState(() {
     //The state that has changed here is the animation object’s value.
   });
});
  • ビルドインウィジェット、AnimatedWidgetおよびAnimatedBuilderを使用して、このプロセスをスキップできます。 両方のウィジェットはAnimationオブジェクトを受け入れ、アニメーションに必要な現在の値を取得します。
  • ウィジェットのビルドプロセス中にアニメーション値を取得し、元の値の代わりに幅、高さ、または関連するプロパティに適用します。
child: Container(
   height: animation.value,
   width: animation.value,
   child: <Widget>,
)

実用的なアプリケーション

Flutterフレームワークのアニメーションの概念を理解するために、簡単なアニメーションベースのアプリケーションを作成しましょう。

  • Androidスタジオでproduct_animation_appに新しい_Flutter_アプリケーションを作成します。
  • アセットフォルダーをproduct_nav_appからproduct_animation_appにコピーし、pubspec.yamlファイル内にアセットを追加します。
flutter:
   assets:
   - assets/appimages/floppy.png
   - assets/appimages/iphone.png
   - assets/appimages/laptop.png
   - assets/appimages/pendrive.png
   - assets/appimages/pixel.png
   - assets/appimages/tablet.png
  • デフォルトの起動コード(main.dart)を削除します。
  • インポートと基本的なメイン機能を追加します。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
  • StatefulWidgtetから派生したMyAppウィジェットを作成します。
class MyApp extends StatefulWidget {
   _MyAppState createState() => _MyAppState();
}
  • _MyAppStateウィジェットを作成し、デフォルトのビルドメソッドに加えてinitStateを実装して破棄します。
class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
   Animation<double> animation;
   AnimationController controller;
   @override void initState() {
      super.initState();
      controller = AnimationController(
         duration: const Duration(seconds: 10), vsync: this
      );
      animation = Tween<double>(begin: 0.0, end: 1.0).animate(controller);
      controller.forward();
   }
  //This widget is the root of your application.
   @override
   Widget build(BuildContext context) {
      controller.forward();
      return MaterialApp(
         title: 'Flutter Demo',
         theme: ThemeData(primarySwatch: Colors.blue,),
         home: MyHomePage(title: 'Product layout demo home page', animation: animation,)
      );
   }
   @override
   void dispose() {
      controller.dispose();
      super.dispose();
   }
}

ここに、

  • initStateメソッドでは、アニメーションコントローラーオブジェクト(コントローラー)、アニメーションオブジェクト(アニメーション)を作成し、controller.forwardを使用してアニメーションを開始しました。
  • disposeメソッドでは、アニメーションコントローラーオブジェクト(コントローラー)を破棄しました。
  • buildメソッドで、コンストラクターを介してMyHomePageウィジェットにアニメーションを送信します。 これで、MyHomePageウィジェットはアニメーションオブジェクトを使用してそのコンテンツをアニメーション化できます。
  • 次に、ProductBoxウィジェットを追加します
class ProductBox extends StatelessWidget {
   ProductBox({Key key, this.name, this.description, this.price, this.image})
      : super(key: key);
   final String name;
   final String description;
   final int price;
   final String image;

   Widget build(BuildContext context) {
      return Container(
         padding: EdgeInsets.all(2),
         height: 140,
         child: Card(
            child: Row(
               mainAxisAlignment: MainAxisAlignment.spaceEvenly,
               children: <Widget>[
                  Image.asset("assets/appimages/" + image),
                  Expanded(
                     child: Container(
                        padding: EdgeInsets.all(5),
                        child: Column(
                           mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                           children: <Widget>[
                              Text(this.name, style:
                                 TextStyle(fontWeight: FontWeight.bold)),
                              Text(this.description),
                                 Text("Price: " + this.price.toString()),
                           ],
                        )
                     )
                  )
               ]
            )
         )
      );
   }
}
  • 新しいウィジェットMyAnimatedWidgetを作成して、不透明度を使用した単純なフェードアニメーションを作成します。
class MyAnimatedWidget extends StatelessWidget {
   MyAnimatedWidget({this.child, this.animation});

   final Widget child;
   final Animation<double> animation;

   Widget build(BuildContext context) => Center(
   child: AnimatedBuilder(
      animation: animation,
      builder: (context, child) => Container(
         child: Opacity(opacity: animation.value, child: child),
      ),
      child: child),
   );
}
  • ここでは、AniatedBuilderを使用してアニメーションを作成しました。 AnimatedBuilderは、同時にアニメーションを実行しながらコンテンツを構築するウィジェットです。 アニメーションオブジェクトを受け入れて、現在のアニメーション値を取得します。 アニメーション値、animation.valueを使用して、子ウィジェットの不透明度を設定しました。 実際には、ウィジェットは不透明度の概念を使用して子ウィジェットをアニメーション化します。
  • 最後に、MyHomePageウィジェットを作成し、アニメーションオブジェクトを使用してそのコンテンツをアニメーション化します。
class MyHomePage extends StatelessWidget {
   MyHomePage({Key key, this.title, this.animation}) : super(key: key);

   final String title;
   final Animation<double>
   animation;

   @override
   Widget build(BuildContext context) {
      return Scaffold(
         appBar: AppBar(title: Text("Product Listing")),body: ListView(
            shrinkWrap: true,
            padding: const EdgeInsets.fromLTRB(2.0, 10.0, 2.0, 10.0),
            children: <Widget>[
               FadeTransition(
                  child: ProductBox(
                     name: "iPhone",
                     description: "iPhone is the stylist phone ever",
                     price: 1000,
                     image: "iphone.png"
                  ), opacity: animation
               ),
               MyAnimatedWidget(child: ProductBox(
                  name: "Pixel",
                  description: "Pixel is the most featureful phone ever",
                  price: 800,
                  image: "pixel.png"
               ), animation: animation),
               ProductBox(
                  name: "Laptop",
                  description: "Laptop is most productive development tool",
                  price: 2000,
                  image: "laptop.png"
               ),
               ProductBox(
                  name: "Tablet",
                  description: "Tablet is the most useful device ever for meeting",
                  price: 1500,
                  image: "tablet.png"
               ),
               ProductBox(
                  name: "Pendrive",
                  description: "Pendrive is useful storage medium",
                  price: 100,
                  image: "pendrive.png"
               ),
               ProductBox(
                  name: "Floppy Drive",
                  description: "Floppy drive is useful rescue storage medium",
                  price: 20,
                  image: "floppy.png"
               ),
            ],
         )
      );
   }
}

ここでは、FadeAnimationとMyAnimationWidgetを使用して、リストの最初の2つのアイテムをアニメーション化しました。 FadeAnimationはビルドインアニメーションクラスであり、不透明度の概念を使用して子をアニメーション化するために使用しました。

  • 完全なコードは次のとおりです-
import 'package:flutter/material.dart';
void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
   _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
   Animation<double> animation;
   AnimationController controller;

   @override
   void initState() {
      super.initState();
      controller = AnimationController(
         duration: const Duration(seconds: 10), vsync: this);
      animation = Tween<double>(begin: 0.0, end: 1.0).animate(controller);
      controller.forward();
   }
  //This widget is the root of your application.
   @override
   Widget build(BuildContext context) {
      controller.forward();
      return MaterialApp(
         title: 'Flutter Demo', theme: ThemeData(primarySwatch: Colors.blue,),
         home: MyHomePage(title: 'Product layout demo home page', animation: animation,)
      );
   }
   @override
   void dispose() {
      controller.dispose();
      super.dispose();
   }
}
class MyHomePage extends StatelessWidget {
   MyHomePage({Key key, this.title, this.animation}): super(key: key);
   final String title;
   final Animation<double> animation;

   @override
   Widget build(BuildContext context) {
      return Scaffold(
         appBar: AppBar(title: Text("Product Listing")),
         body: ListView(
            shrinkWrap: true,
            padding: const EdgeInsets.fromLTRB(2.0, 10.0, 2.0, 10.0),
            children: <Widget>[
               FadeTransition(
                  child: ProductBox(
                     name: "iPhone",
                     description: "iPhone is the stylist phone ever",
                     price: 1000,
                     image: "iphone.png"
                  ),
                  opacity: animation
               ),
               MyAnimatedWidget(
                  child: ProductBox(
                     name: "Pixel",
                     description: "Pixel is the most featureful phone ever",
                     price: 800,
                     image: "pixel.png"
                  ),
                  animation: animation
               ),
               ProductBox(
                  name: "Laptop",
                  description: "Laptop is most productive development tool",
                  price: 2000,
                  image: "laptop.png"
               ),
               ProductBox(
                  name: "Tablet",
                  description: "Tablet is the most useful device ever for meeting",
                  price: 1500,
                  image: "tablet.png"
               ),
               ProductBox(
                  name: "Pendrive",
                  description: "Pendrive is useful storage medium",
                  price: 100,
                  image: "pendrive.png"
               ),
               ProductBox(
                  name: "Floppy Drive",
                  description: "Floppy drive is useful rescue storage medium",
                  price: 20,
                  image: "floppy.png"
               ),
            ],
         )
      );
   }
}
class ProductBox extends StatelessWidget {
   ProductBox({Key key, this.name, this.description, this.price, this.image}) :
      super(key: key);
   final String name;
   final String description;
   final int price;
   final String image;
   Widget build(BuildContext context) {
      return Container(
         padding: EdgeInsets.all(2),
         height: 140,
         child: Card(
            child: Row(
               mainAxisAlignment: MainAxisAlignment.spaceEvenly,
               children: <Widget>[
                  Image.asset("assets/appimages/" + image),
                  Expanded(
                     child: Container(
                        padding: EdgeInsets.all(5),
                        child: Column(
                           mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                           children: <Widget>[
                              Text(
                                 this.name, style: TextStyle(
                                    fontWeight: FontWeight.bold
                                 )
                              ),
                              Text(this.description), Text(
                                 "Price: " + this.price.toString()
                              ),
                           ],
                        )
                     )
                  )
               ]
            )
         )
      );
   }
}
class MyAnimatedWidget extends StatelessWidget {
   MyAnimatedWidget({this.child, this.animation});
   final Widget child;
   final Animation<double> animation;

   Widget build(BuildContext context) => Center(
      child: AnimatedBuilder(
         animation: animation,
         builder: (context, child) => Container(
            child: Opacity(opacity: animation.value, child: child),
         ),
         child: child
      ),
   );
}
  • アプリケーションをコンパイルして実行し、結果を確認します。 アプリケーションの初期および最終バージョンは次のとおりです-

初期バージョン

最終バージョン