56

Flutter中是否有任何内置方法可以在向下滚动时隐藏a ,然后FloatingActionButtonListView向上滚动时显示它?

4

9 回答 9

77
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
 }
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
 }

 class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  ScrollController _hideButtonController;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
  var _isVisible;
  @override
  initState(){
    super.initState();
    _isVisible = true;
    _hideButtonController = new ScrollController();
    _hideButtonController.addListener((){
      if(_hideButtonController.position.userScrollDirection == ScrollDirection.reverse){
        if(_isVisible == true) {
            /* only set when the previous state is false
             * Less widget rebuilds 
             */
            print("**** ${_isVisible} up"); //Move IO away from setState
            setState((){
              _isVisible = false;
            });
        }
      } else {
        if(_hideButtonController.position.userScrollDirection == ScrollDirection.forward){
          if(_isVisible == false) {
              /* only set when the previous state is false
               * Less widget rebuilds 
               */
               print("**** ${_isVisible} down"); //Move IO away from setState
               setState((){
                 _isVisible = true;
               });
           }
        }
    }});
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new CustomScrollView(
          controller: _hideButtonController,
          shrinkWrap: true,
          slivers: <Widget>[
            new SliverPadding(
              padding: const EdgeInsets.all(20.0),
              sliver: new SliverList(
                delegate: new SliverChildListDelegate(
                  <Widget>[
                    const Text('I\'m dedicating every day to you'),
                    const Text('Domestic life was never quite my style'),
                    const Text('When you smile, you knock me out, I fall apart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('And I thought I was so smart'),
                    const Text('I realize I am crazy'),   
                  ],
                ),
              ),
            ),
          ],
        )
      ),
      floatingActionButton: new Visibility( 
        visible: _isVisible,
        child: new FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: new Icon(Icons.add),
        ),     
      ),
    );
  }
}

如果我没有使用 listview,我深表歉意,因为我不知道如何使用 listview 滚动。我会回答你问题的其他部分。

首先你需要创建一个滚动控制器来监听scrollPostion事件

如果滚动控制器设法找到向前或向后滚动方向。您添加一个将状态设置为可见的状态。

绘制按钮时,将按钮包装在可见性类中。您设置了可见标志,小部件应忽略输入命令。

编辑:我似乎无法添加指向 ScrollController、ScrollerPosition、ScrollDirection 和 Opacity 的链接。我想您可以自己搜索或其他人在链接中进行编辑

Edit2:使用 CopsonRoad 或使用可见性小部件,除非您想在布局树中使用未绘制的小部件

Edit3:鉴于新来者按原样使用代码,我会更新代码以鼓励更好的实践。使用可见性而不是不透明度。从 setState 中移除 io。在 Flutter 1.5.4-hotfix.2 上测试

于 2017-08-15T21:51:54.017 回答
30

没有动画:

  • 使用Visibility小部件:

    floatingActionButton: Visibility(
      visible: false, // Set it to false
      child: FloatingActionButton(...),
    )
    
  • 使用Opacity小部件:

    floatingActionButton: Opacity(
      opacity: 0, // Set it to 0
      child: FloatingActionButton(...),
    )
    
  • 使用三元运算符:

    floatingActionButton: shouldShow ? FloatingActionButton() : null,
    
  • 使用if条件:

    floatingActionButton: Column(
      children: <Widget>[
        if (shouldShow) FloatingActionButton(...), // Visible if condition is true
      ],
    )
    

带动画:

在此处输入图像描述

这只是使用动画的一个示例,您可以使用这种方法创建不同类型的 UI。

bool _showFab = true;
  
@override
Widget build(BuildContext context) {
  const duration = Duration(milliseconds: 300);
  return Scaffold(
    floatingActionButton: AnimatedSlide(
      duration: duration,
      offset: _showFab ? Offset.zero : Offset(0, 2),
      child: AnimatedOpacity(
        duration: duration,
        opacity: _showFab ? 1 : 0,
        child: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {},
        ),
      ),
    ),
    body: NotificationListener<UserScrollNotification>(
      onNotification: (notification) {
        final ScrollDirection direction = notification.direction;
        setState(() {
          if (direction == ScrollDirection.reverse) {
            _showFab = false;
          } else if (direction == ScrollDirection.forward) {
            _showFab = true;
          }
        });
        return true;
      },
      child: ListView.builder(
        itemCount: 100,
        itemBuilder: (_, i) => ListTile(title: Text('$i')),
      ),
    ),
  );
}
于 2018-10-10T01:47:05.440 回答
29

相当老的问题,但在我看来,最新的颤振有一个更好(和更短)的解决方案。

其他解决方案确实有效,但如果你想要一个漂亮的动画(类似于 Android 中的默认动画),你可以这样做:

每当用户滚动(向上/向下)时,NotificationListener 都会通知您。使用 AnimationController,您可以控制 FAB 的动画。

这是一个完整的例子:

class WidgetState extends State<Widget> with TickerProviderStateMixin<Widget> {
  AnimationController _hideFabAnimation;

  @override
  initState() {
    super.initState();
    _hideFabAnimation = AnimationController(vsync: this, duration: kThemeAnimationDuration);
  }

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

  bool _handleScrollNotification(ScrollNotification notification) {
    if (notification.depth == 0) {
      if (notification is UserScrollNotification) {
        final UserScrollNotification userScroll = notification;
        switch (userScroll.direction) {
          case ScrollDirection.forward:
            if (userScroll.metrics.maxScrollExtent !=
                userScroll.metrics.minScrollExtent) {
              _hideFabAnimation.forward();
            }
            break;
          case ScrollDirection.reverse:
           if (userScroll.metrics.maxScrollExtent !=
                userScroll.metrics.minScrollExtent) {
              _hideFabAnimation.reverse();
            }
            break;
          case ScrollDirection.idle:
            break;
        }
      }
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener<ScrollNotification>(
      onNotification: _handleScrollNotification,
      child: Scaffold(
        appBar: AppBar(
          title: Text('Fabulous FAB Animation')
        ),
        body: Container(),
        floatingActionButton: ScaleTransition(
          scale: _hideFabAnimation,
          alignment: Alignment.bottomCenter,
          child: FloatingActionButton(
            elevation: 8,
            onPressed: () {},
            child: Icon(Icons.code),
          ),
        ),
      ),
    );
  }
}
于 2019-12-19T11:00:02.110 回答
12

一个很好的方法...

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  ScrollController controller;
  bool fabIsVisible = true;

  @override
  void initState() {
    super.initState();
    controller = ScrollController();
    controller.addListener(() {
      setState(() {
        fabIsVisible =
            controller.position.userScrollDirection == ScrollDirection.forward;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        controller: controller,
        children: List.generate(
            100,
            (index) => ListTile(
                  title: Text("Text $index"),
                )),
      ),
      floatingActionButton: AnimatedOpacity(
        child: FloatingActionButton(
          child: Icon(Icons.add),
          tooltip: "Increment",
          onPressed: !fabIsVisible ? null: () {
            print("Pressed");
          },
        ),
        duration: Duration(milliseconds: 100),
        opacity: fabIsVisible ? 1 : 0,
      ),
    );
  }
}
于 2020-03-10T14:02:29.747 回答
8

您可以使用下面的代码来保留默认动画

floatingActionButton: _isVisible
        ? FloatingActionButton(...)
        : null,
于 2020-02-03T06:24:19.490 回答
6

您可以使用Visibility小部件来处理子小部件的可见性

样本 :

  floatingActionButton:
            Visibility(visible: _visibilityFlag , child: _buildFAB(context)),
于 2019-03-13T06:27:02.503 回答
5

其他非常好的方法是AnimatedOpacity

AnimatedOpacity(
          opacity: isEnabled ? 0.0 : 1.0,
          duration: Duration(milliseconds: 1000),
          child: FloatingActionButton(
             onPressed: your_method,
             tooltip: 'Increment',
             child: new Icon(Icons.add),
          ),
        )
于 2019-09-05T19:00:14.580 回答
0

@Josteve 的答案是正确的,但setState()每次用户滚动时调用并不是一个好主意。更好的方法如下所示:

import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  ScrollController controller;
  bool _isFabVisible = true;

  @override
  void initState() {
    super.initState();
    controller = ScrollController();
    controller.addListener(() {
      // FAB should be visible if and only if user has not scrolled to bottom
      var userHasScrolledToBottom = controller.position.atEdge && controller.position.pixels > 0;

      if(_isFabVisible == userHasScrolledToBottom) {
        setState(() => _isFabVisible = !userHasScrolledToBottom);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        controller: controller,
        children: List.generate(
            100,
            (index) => ListTile(
                  title: Text("Text $index"),
                )),
      ),
      floatingActionButton: AnimatedOpacity(
        child: FloatingActionButton(
          child: Icon(Icons.add),
          tooltip: "Increment",
          onPressed: () {
            print("Pressed");
          },
        ),
        duration: Duration(milliseconds: 100),
        opacity: _isFabVisible? 1 : 0,
      ),
    );
  }
}
于 2021-09-26T18:22:41.013 回答
0

对于任何使用 Rxdart 的人来说,有一种简洁的方法可以做到这一点,并且它带有额外的方便工具。

首先,将滚动位置转换为流,您以后也可以重用此方法。


extension ScrollControllerX on ScrollController {
  Stream<double> positionAsStream() {
    late StreamController<double> controller;

    void addListener() => controller.add(position.pixels);
    void onListen() => this.addListener(addListener);
    void onCancel() {
      removeListener(addListener);
      controller.close();
    }

    controller = StreamController<double>(onListen: onListen, onCancel: onCancel);

    return controller.stream;
  }
}

像这样使用它。


      @override
      void initState() {
        super.initState();
        final subscription = scrollController
            .positionAsStream()
            .pairwise()
            .map((p) => p.last > p.first)
            .distinct() // If direction don't change, skip it 
            .listen((down) => down ? hideFabAnimationController.forward() : hideFabAnimationController.reverse());
    }



    FadeTransition(
                opacity: hideFabAnimationController,
                child: ScaleTransition(
                  scale: hideFabAnimationController,
                  child: FloatingActionButton(
                    onPressed: () => {},
                    child: const Icon(Icons.add),
                  ),
                ),
              )

并且不要忘记取消订阅!


      @override
      void dispose() {
        subscription.cancel();
      }

当用户滚动得太快时,您可以执行其他操作,例如限制流。

于 2022-01-03T10:55:16.903 回答