ListView-监听滑动

import 'dart:math';

import 'package:flutter/material.dart';

main() => runApp(Demo01App());

class Demo01App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RootPage();
  }
}

class RootPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

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

class _HomePageState extends State {
  ScrollController listViewListenerController =
      ScrollController(initialScrollOffset: 300.0);
  bool isShowFloatingButton = false;

  @override
  void initState() {
    super.initState();
    listViewListenerController.addListener(() {
      print("监听到 ListView 滚动到${listViewListenerController.offset}的位置");
      if(listViewListenerController.offset > 800){
        setState(() {
          isShowFloatingButton = true;
        });
      }else{
        setState(() {
          isShowFloatingButton = false;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    /**
     * 两种方法监听:
     *  controller:
     *    1.可以设置默认 offset 默认显示的位置
     *    2.可以滚动,也可以监听滚动的位置
     *
     *    -不可以监听开始滚动、结束滚动
     *
     *  NotifycationListener
     *    1.可以设置默认 offset 默认显示的位置
     *    2.可以滚动,也可以监听滚动的位置
     *    3.可以监听开始滚动、结束滚动
     */

    return Scaffold(
      appBar: AppBar(
        title: Text("多列表"),
      ),
      floatingActionButton: isShowFloatingButton
          ? IconButton(
              icon: Icon(Icons.arrow_upward),
              onPressed: () {
                setState(() {
                  listViewListenerController.animateTo(0,
                      duration: Duration(seconds: 1), curve: Curves.easeIn);
                });
              })
          : null,
      body: NotificationListener(
        onNotification: (ScrollNotification notification) {
//          print("监听到滚动");
          if (notification is ScrollStartNotification) {
            print("开始滚动");
          }
          if (notification is ScrollUpdateNotification) {
            print(
                "正在滚动...  , 当前滚动的位置 ${notification.metrics.pixels}  ListView总高度${notification.metrics.maxScrollExtent}");
          }
          if (notification is ScrollEndNotification) {
            print("结束滚动");
          }
          return true; //返回 true 表示监听到的方法不向上冒泡
        },
        child: ListView.builder(
            controller: listViewListenerController,
            itemCount: 100,
            itemBuilder: (BuildContext ctx, int index) {
              return ListTile(
                leading: Icon(Icons.people),
                title: Text("联系人$index"),
              );
            }),
      ),
    );
  }
  @override
  void dispose() {
    super.dispose();
    listViewListenerController.dispose();//释放 controller
  }
}

你可能感兴趣的:(ListView-监听滑动)