handle scroll direction in flutter

All you need is

ScrollController.position.userScrollDirection

Set up a ScrollController listener and listen for direction. Here is the full code.


bool upDirection = true, flag = true;
ScrollController _controller;

@override
void initState() {
  super.initState();
  _controller = ScrollController()
    ..addListener(() {
      upDirection = _controller.position.userScrollDirection == ScrollDirection.forward;

      // makes sure we don't call setState too much, but only when it is needed
      if (upDirection != flag) 
        setState(() {});


      flag = upDirection;
    });
}

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

Tags:

Dart

Flutter