1. 程式人生 > 實用技巧 >flutter-路由跳轉動畫效果(漸隱漸現,縮放效果,旋轉縮放)

flutter-路由跳轉動畫效果(漸隱漸現,縮放效果,旋轉縮放)

1.漸隱漸現過渡效果

自定義CustomRoute Widget

新建一個custom_router.dart檔案,這個就是要自定義的路由方法,自定義首先要繼承於通用的路由的構造器類PageRouterBuilder。繼承之後重寫父類的CustomRoute構造方法。

構造方法可以簡單理解為:只要以呼叫這個類或者說是Widget,構造方法裡的所有程式碼就執行了。

import 'package:flutter/material.dart';


//自定義的路由方法
class CustomRoute extends PageRouteBuilder{

  final Widget widget;

  
//重寫構造方法(一呼叫該方法就執行的方法 就叫構造方法) CustomRoute(this.widget) :super( //父類的方法 //設定動畫持續的時間,建議再1和2之間 transitionDuration:const Duration(seconds: 1), //頁面的構造器 pageBuilder:( BuildContext context, Animation<double> animation1, Animation<double> animation2, ){
return widget; }, //過度效果 transitionsBuilder:( BuildContext context, Animation<double> animation1, Animation<double> animation2, Widget child ){ // 過度的動畫的值 return FadeTransition( // 過度的透明的效果 opacity: Tween(begin: 0.0,end: 1.0)
// 給他個透明度的動畫 CurvedAnimation:設定動畫曲線 .animate(CurvedAnimation( //父級動畫 parent: animation1, //動畫曲線 curve: Curves.ease )), child: child, ); }); }


//使用
import'custom_router.dart'; Navigator.push(context,CustomRoute(SecondPage()));
  • FadeTransition:漸隱漸現過渡效果,主要設定opactiy(透明度)屬性,值是0.0-1.0。
  • animate :動畫的樣式,一般使用動畫曲線元件(CurvedAnimation)。

  • curve: 設定動畫的節奏,也就是常說的曲線,Flutter準備了很多節奏,通過改變動畫取消可以做出很多不同的效果。

  • transitionDuration:設定動畫持續的時間,建議再1和2之間。

2.縮放效果

//縮放的動畫效果
        return ScaleTransition(
          scale: Tween(begin: 0.0,end: 1.0)
            .animate(CurvedAnimation(
              parent: animation1,
              //快出慢進
              curve: Curves.fastOutSlowIn
            )),
            child: child,
        );

3.旋轉+縮放效果

//旋轉+縮放效果
        return RotationTransition(
          turns: Tween(begin: 0.0,end: 1.0)
            .animate(CurvedAnimation(
              parent: animation1,
              curve: Curves.fastOutSlowIn
            )),
            child: ScaleTransition(
              scale: Tween(begin: 0.0,end: 1.0)
                .animate(CurvedAnimation(
                  parent: animation1,
                  curve: Curves.fastOutSlowIn
                )),
              child: child,
            ),
        );

4.左右切換滑動

//左右滑動切換
        return SlideTransition(
          //定義滑動的位置
          position: Tween<Offset>(begin: Offset(-1.0,0.0),end: Offset(0.0,0.0))
            .animate(CurvedAnimation(
              parent: animation1,
              curve: Curves.fastOutSlowIn
            )),
            child: child,
        );