Flutter – リストのスクロールイベント

今回、一番下までスクロールしたらボタンが活性になる仕様があったのですが、調べた内容をメモしたいと思います。

スクロールイベント

スクロールイベントを拾うためには「NotificationListener」で「SingleChildScrollView」や「ListView」などをマッピングする必要があるらしいです。

NotificationListener<ScrollNotification>(
          child: SingleChildScrollView(
            child: Text(
              item,
              style: const TextStyle(
                fontSize: 22.0,
                color: Colors.black,
              ),
            ),
          ),
        ),

「NotificationListener」のプロパティに「onNotification」がありますがこのプロパティを使ってスクロール情報を取得できます。

          onNotification: (ScrollNotification notification) {
            print('OverscrollNotification:${notification is OverscrollNotification}');
            print('maxScrollExtent:${notification.metrics.maxScrollExtent}');
            print('pixels:${notification.metrics.pixels}');
            print('outOfRange:${notification.metrics.outOfRange}');

            return false;
          },
  • notification is OverscrollNotification
    • 最上位または最下位にスクロールしたときに「true」になります。
  • notification.metrics.maxScrollExtent
    • 最下位のスクロール値です。(double)
  • notification.metrics.pixels
    • 現在、スクロールの位置の値です。(double)
  • notification.metrics.outOfRange
    • 最上位または最下位にスクロールしたときに「true」になります。

注意点

「notification is OverscrollNotification」と「notification.metrics.outOfRange」は何が違うかというと「OverscrollNotification」はIOSで呼ばれないです。IOSもAndroidもオーバースクロールを対応するためには「notification.metrics.outOfRange」こちらを使えばいいでしょう。

解決

今回の使用は一番上ではなく、一番下にスクロールしたときにボタンを活性にするしようだったので以下のように解決しました。

onNotification: (ScrollNotification notification) {
            if (notification.metrics.maxScrollExtent <=
                notification.metrics.pixels) {
              // ボタンを活性化する。
            }
            return false;
},

コメントを残す