flutter 滚动监听

本文最后更新于:2022年4月22日 上午

flutter 滚动监听

ScrollController

  1. 先创建一个 ScrollController
  2. 然后在 initState中监听滚动
  3. ListView或者 GridView中的 controller 中将其传入
  4. dispose中取消监听

_scrollController.offset中可以获取到当前滚动的距离

_scrollController.animateTo 可以滚动到指定距离

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 监听滚动,初始化滚动距离
  final ScrollController _scrollController = ScrollController(initialScrollOffset: 200);
  bool showTop = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      print('开始滚动, 当前滚动距离${_scrollController.offset}');
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.builder(
        itemCount: 100,
        controller: _scrollController,
        gridDelegate:
            SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 100, mainAxisSpacing: 5, crossAxisSpacing: 5),
        itemBuilder: (BuildContext context, index) {
          return Container(
            width: 100,
            height: 100,
            color: Color.fromRGBO(
                Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), Random().nextInt(10) / 10),
          );
        },
      ),
      floatingActionButton: showTop
          ? FloatingActionButton(
              child: Icon(Icons.vertical_align_top),
              onPressed: () {
                // 回到顶部
                _scrollController.animateTo(0, duration: Duration(milliseconds: 600), curve: Curves.ease);
              },
            )
          : null,
    );
  }

floatingActionButton

floatingActionButton为屏幕右下角的位置按钮

NotificationListener

NotificationListener的方式和 ScrollController 不太一样

NotificationListener为在onNotification中监听不同的事件来做不同的判断,

return NotificationListener(
    onNotification: (ScrollNotification scrollNotification) {
      // 通过 is 关键字来判断所属类
      if (scrollNotification is ScrollStartNotification) {
        print('开始滚动');
      } else if (scrollNotification is ScrollUpdateNotification) {
        print('滚动中 当前滚动: ${scrollNotification.metrics.pixels}');
      } else if (scrollNotification is ScrollEndNotification) {
        print('结束滚动');
      }

      return true;
    },
    child: GridView.builder(
      itemCount: 100,
      gridDelegate:
          SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 100, mainAxisSpacing: 5, crossAxisSpacing: 5),
      itemBuilder: (BuildContext context, index) {
        return Container(
          width: 100,
          height: 100,
          color: Color.fromRGBO(
              Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), Random().nextInt(10) / 10),
        );
      },
    ),
  );

is操作符

is操作符为校验不同的类型


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议,转载请注明出处。