美文网首页
26.Flutter的ListView监听滚动事件之Notifi

26.Flutter的ListView监听滚动事件之Notifi

作者: 凯司机 | 来源:发表于2020-06-10 15:39 被阅读0次

    如果我们希望监听什么时候开始滚动,什么时候结束滚动,这个时候我们可以通过NotificationListener。

    NotificationListener是一个Widget,模板参数T是想监听的通知类型,如果省略,则所有类型通知都会被监听,如果指定特定类型,则只有该类型的通知会被监听。

    NotificationListener需要一个onNotification回调函数,用于实现监听处理逻辑。

    该回调可以返回一个布尔值,代表是否阻止该事件继续向上冒泡,如果为true时,则冒泡终止,事件停止向上传播,如果不返回或者返回值为false 时,则冒泡继续。

    案例: 列表滚动, 并且在中间显示滚动进度

    classMyHomeNotificationDemoextendsStatefulWidget{

      @override

      State<StatefulWidget> createState() => MyHomeNotificationDemoState();

    }

    classMyHomeNotificationDemoStateextendsState{

      int _progress = 0;

      @override

      Widget build(BuildContext context) {

        return NotificationListener(

          onNotification: (ScrollNotification notification) {

            // 1.判断监听事件的类型

            if (notification is ScrollStartNotification) {

              print("开始滚动.....");

            } elseif (notification is ScrollUpdateNotification) {

              // 当前滚动的位置和总长度

              final currentPixel = notification.metrics.pixels;

              final totalPixel = notification.metrics.maxScrollExtent;

              double progress = currentPixel / totalPixel;

              setState(() {

                _progress = (progress * 100).toInt();

              });

              print("正在滚动:${notification.metrics.pixels}-${notification.metrics.maxScrollExtent}");

            } elseif (notification is ScrollEndNotification) {

              print("结束滚动....");

            }

            returnfalse;

          },

          child: Stack(

            alignment: Alignment(.9, .9),

            children: <Widget>[

              ListView.builder(

                itemCount: 100,

                itemExtent: 60,

                itemBuilder: (BuildContext context, int index) {

                  return ListTile(title: Text("item$index"));

                }

              ),

              CircleAvatar(

                radius: 30,

                child: Text("$_progress%"),

                backgroundColor: Colors.black54,

              )

            ],

          ),

        );

      }

    }

    相关文章

      网友评论

          本文标题:26.Flutter的ListView监听滚动事件之Notifi

          本文链接:https://www.haomeiwen.com/subject/vlrptktx.html