[Flutter-26] NotificationListener 监听滚动二

NotificationListener

/* ScrollNotification

如果我们想要监听什么时候滚动、什么时候结束、这个时候通过NotificationListenr

- NotificationListener是一个Widget、模板参数T是想监听的通知类型、如果省略,则所有类型的通知都会被监听
如果指定特定类型、则只有该类型的通知被监听。
- NotificationListener 需要一个onNotification回调函数、用于实现监听处理逻辑
- 该回调可以返回一个布尔值、代表是否阻止该事件继续向上冒泡,
如果为true:冒泡终止、事件停止向上传播。
如果不返回或者返回值为false:冒泡继续

案例:
  列表滚动、并且右下角显示滚动进度

*/
class Content2 extends StatefulWidget {
  @override
  _Content2State createState() => _Content2State();
}

class _Content2State extends State<Content2> {
  int _progress = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener(
      onNotification: (ScrollNotification notification) {
        // 1. 判断监听的类型
        if (notification is ScrollStartNotification) {
          print('开始滚动...');
        } else if (notification is ScrollUpdateNotification) {
          // 当前滚动的位置和长度
          final currentPixel = notification.metrics.pixels;
          final totalPixel = notification.metrics.maxScrollExtent;
          double progress = currentPixel / totalPixel;
          setState(() {
            _progress = (progress * 100).toInt();
          });

          print('正在滚动: currentPixel=$currentPixel totalPixel=$totalPixel');
        } else if (notification is ScrollEndNotification) {
          print('结束滚动...');
        }

        return false;
      },
      child: Stack(
        alignment: Alignment(0, 0),
        children: [
          ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              return ListTile(
                title: Text('item$index'),
              );
            },
            itemCount: 100,
            itemExtent: 80,
          ),
          CircleAvatar(
            child: Text('$_progress%'),
            backgroundColor: Colors.black,
            radius: 30,
          ),
        ],
      ),
    );
  }
}

posted @ 2021-07-20 17:15  comefromchina  阅读(708)  评论(0)    收藏  举报