首页 > 解决方案 > 如何处理 ListView 滚动方向

问题描述

我有一个项目的虚拟列表,我想在向上滑动方向显示一个浮动操作按钮并在向下方向隐藏它。我怎样才能实现这个功能?

class _MyHomePageState extends State<MyHomePage> {
  bool upDirection = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Container(
          child: Row(
            children: <Widget>[
              Expanded(
                  child: ListView.builder(
                    itemCount: 100,
                    itemBuilder: (context,index){
                      return ListTile(
                        title: Text(index.toString()),
                      );
                    },
                  ),
              )
            ],
          ),
        ),
      ),
      floatingActionButton:upDirection==true?FloatingActionButton(onPressed: (){},):Container() ,
    );
  }
}

标签: flutterdartflutter-layout

解决方案


截屏:

在此处输入图像描述

您只需要一个NotificationListener.onNotification回调:

NotificationListener<UserScrollNotification>(
  onNotification: (notification) {
    final ScrollDirection direction = notification.direction;
    return true;
  },
  child: ListView.builder(
    itemCount: 100,
    itemBuilder: (_, i) => ListTile(title: Text('$i')),
  ),
)

完整代码:

bool _visible = true;
  
@override
Widget build(BuildContext context) {
  return Scaffold(
    floatingActionButton: AnimatedOpacity(
      duration: Duration(milliseconds: 400),
      opacity: _visible ? 1 : 0,
      child: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {},
      ),
    ),
    body: NotificationListener<UserScrollNotification>(
      onNotification: (notification) {
        final ScrollDirection direction = notification.direction;
        setState(() {
          if (direction == ScrollDirection.reverse) {
            _visible = false;
          } else if (direction == ScrollDirection.forward) {
            _visible = true;
          }
        });
        return true;
      },
      child: ListView.builder(
        itemCount: 100,
        itemBuilder: (_, i) => ListTile(title: Text('$i')),
      ),
    ),
  );
}

推荐阅读