Flutter動画やってみよ(Foodアプリ)3/5
画面遷移を作る
遷移先のページを用意します。
lib/pages 以下に、HomePage.dart を作成します。
st[enter] のショートカットから、StatefulWidget を選択し、クラス名をHomePage とします。
しばらく、HomePageを編集していくので、確認しやすいように初期ページをHomePageに変えておきます。
void main() => runApp( MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData(fontFamily: 'Roboto'), home: HomePage(), ) );
まずは、何もない黄色の背景ページとしておきます。
import 'package:flutter/material.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( body: Container( color: Colors.yellow, ), ); } }
StartPage に、画面遷移処理を追加する
画面遷移のアニメーションパッケージを import して、初期化します。
AnimationControllerと、Animation の初期化を行います。
import 'package:page_transition/page_transition.dart'; ... class _StarterPageState extends State<StarterPage> with TickerProviderStateMixin{ AnimationController _animationController; Animation<double> _animation; bool _textVisible = true; @override void initState() { _animationController = AnimationController( vsync: this, duration: Duration(milliseconds: 100) ); _animation = Tween<double>( begin: 0.0, end: 25.0 ).animate(_animationController); super.initState(); } @override void dispose() { _animationController.dispose(); super.dispose(); }
Startボタンが押されたら画面遷移するように、関数を追加します。
void _onTap() { setState(() { _textVisible = false; }); _animationController.forward().then((f) => Navigator.push(context, PageTransition(type: PageTransitionType.fade, child: HomePage())) ); }
最後に、ボタンが押されたら _onTap() を呼びます。
child: MaterialButton( onPressed: () => _onTap(),
リロードして、Startボタンを押してみます。
iPhone 11 Proでも、そこまで滑らかではないのが気になる…
最後に、もう少しアニメーションを追加します。
FadeAnimation に渡していたContainer を、ScaleTransitionで囲みます。
child: Padding( ... child: Column( ... children: <Widget>[ ... FadeAnimation(1.2, ScaleTransition( scale: _animation, child: Container( decoration: BoxDecoration(
MaterialButtonも、同様に AnimationOpacity で囲みます。
child: Container( ... child: AnimatedOpacity ( opacity: _textVisible ? 1.0 : 0.0, duration: Duration(milliseconds: 50), child: MaterialButton( onPressed: () => _onTap(), minWidth: double.infinity, child: Text("Start", style: TextStyle(color: Colors.white),), ), )
Youtubeを見てると、ボタンを押すと
文字が大きくなりつつアニメーションするようですが…
シュミレーターでは、カクカクしすぎてわかりませんでした…
アニメーション重いな…
つづきます。
完成したら、改めて振り返ってみよう。