Skip to content

[Flutter] 使用 FadeTransition 將元件設置閃爍動畫

FadeTransition 是我在學習 Flutter 的元件動畫時湊巧看到一種動畫效果,雖然目前為止都沒有應用到這個效果的需求,不過既然都研究了怎麼使用,也還挺簡單有趣的,便順手記錄下來。

簡單來說,FadeTransition 跟我之前在 [Flutter] 實現元件淡出淡入效果 這篇文章中紀錄的 AnimatedOpacity 有些相似,都是可以控制元件透明度的方法。

唯一的不同之處是,FadeTransition 能設置一個固定的週期,使元件透明度的變化反覆更動,形成一種閃爍的動畫效果。


FadeTransition

FadeTransition 的使用方法非常簡單,跟 Flutter 大部分的元件動畫相似,我們需要準備以下兩種物件:

  • AnimationController:可設定週期之類的參數
  • Animation<double>:可決定動畫執行的 curveFlutter 中 Curves 的選項有非常多種

Animation<double>parent 屬性設定為 AnimationController、而 FadeTransitionopacity 參數又要輸入 Animation<double>。之後,再把要隱藏、顯示的元件放在 FadeTransition 的 child 位置即可。

這樣解釋有點複雜,不過我認為仔細看會發現這都是有道理的。直接看程式碼應該很清楚。

import 'package:flutter/material.dart';

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

// MyApp
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}


// HomePage
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}


// _HomePageState
class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  // Controller
  late AnimationController _controller = AnimationController(
    vsync: this,
    duration: Duration(seconds: 1),
  )..repeat(reverse: true);

  // Animation
  late Animation<double> _animation = CurvedAnimation(
    parent: _controller,
    curve: Curves.easeInOut
  );

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FadeTransition(
          opacity: _animation,
          child: Container(
            height: 100,
            width: 100,
            color: Colors.red,
          ),
        ),
      ),
    );
  }
}


Output:


References


Read More

Tags:

Leave a Reply