【 Flutter 】Flutter を 基礎 から 学習 ( ウィジェット編 ) part91 Scrolling

基礎 から 学ぶ Flutter 」という書籍で  学習 したことを ブログでアウトプットしていこうと思います。今回は ウィジェット編 ( part91 )です。

前回

【 Flutter 】Flutter を 基礎 から 学習 ( ウィジェット編 ) part90 Scrolling

引き続き、Scrollingについて学びます。

Scrolling

PageViewウィジェット

いろいろなプロパティ

controllerプロパティ

controllerプロパティは初期ページの指定をしたりページ遷移時の挙動設定など細やかな実装が可能になります。

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new MyApp()));
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _State();
  }
}

// データ
List<String> items = [
  "images/flutter.jpg",
  "images/flutter_275x86.jpg",
  "images/cat_nekoko.png",
  "images/button.png",
];

class _State extends State<MyApp> {
  // ページコントローラを生成します。
  final PageController controller = PageController(viewportFraction: 0.8);

  // ページインデックスを保持します。
  int currentPage = 0;

  @override
  void initState() {
    super.initState();

    // ページコントローラのページ遷移を監視しページ数を丸める
    controller.addListener(() {
      int next = controller.page!.round();
      if (currentPage != next) {
        setState(() {
          currentPage = next;
        });
      }
    });
  }

  /*
   * アニメーションカード生成
   */
  AnimatedContainer _createCardAnimate(String imagePath, bool active) {
    // アクティブと非アクティブのアニメーション設定値です。
    final double top = active ? 100 : 200;
    final double side = active ? 0 : 40;

    return AnimatedContainer(
      duration: Duration(milliseconds: 500),
      curve: Curves.easeOutQuint,
      margin: EdgeInsets.only(top: top, bottom: 50.0, right: side, left: side),
      decoration: BoxDecoration(
        image: DecorationImage(
          fit: BoxFit.fitWidth,
          image: Image.asset(imagePath).image,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text('テスト中です。'),
      ),
      body: PageView.builder(
        controller: controller,
        itemCount: items.length,
        itemBuilder: (context, int currentIndex) {
          // アクティブ値
          bool active = currentIndex == currentPage;

          // カードの生成して返します。
          return _createCardAnimate(
            items[currentIndex],
            active,
          );
        },
      ),
    ));
  }
}
いい感じのページ遷移ができるようになりましたね!
参考サイトに感謝です😉

 

最後に

リッチな体験ができる実装はとても大事だと思います。

今日はここまで!

参考

【Flutter】PageViewでスライド時にアニメーションさせる実装 | 株式会社イーガオ (egao-inc.co.jp)