flutter 检测SingleChildScrollView是否可滚动

vatpfxk5  于 2022-12-24  发布在  Flutter
关注(0)|答案(1)|浏览(372)

我正在尝试检测我打开的当前屏幕是否可以滚动。我读过一些关于在滚动控制器上使用maxScrollExtent的线程,但在尝试打印hasClient的值时出现了与"未附加scrollController"相关的错误。我认为这与isScrollable的值始终为假有关。
ScrollController未附加到任何滚动视图。
下面是我的代码:

static ScrollController detailCollabScrollController = ScrollController();
    
      void initState() {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          setState(() {
            DevMode.log('attached ? ${MainDetailCollabTicketPage.detailCollabScrollController.hasClients}');
    
            if(MainDetailCollabTicketPage.detailCollabScrollController.position.maxScrollExtent > 0) {
              isScrollable = true;
            }
          });
        });
    
        super.initState();
      }
    
      Widget build(BuildContext context) {
        DevMode.log('isScrollable ? $isScrollable');
    
           return Scaffold(
            /// BODY
            body: NotificationListener<OverscrollIndicatorNotification>(
              onNotification: (overScroll) {
                overScroll.disallowIndicator();
                return true;
              },
              child: SingleChildScrollView(
                controller: MainDetailCollabTicketPage.detailCollabScrollController,
                child: ///Some code for the item,
              ),
            ),
        )
     }
wsewodh2

wsewodh21#

您可以通过向ScrollController添加侦听器来实现这一点。

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      if (_scrollController.offset >= _scrollController.position.maxScrollExtent &&
          !_scrollController.position.outOfRange) {
        print("Reached the bottom");
      }
      if (_scrollController.offset <= _scrollController.position.minScrollExtent &&
          !_scrollController.position.outOfRange) {
        print("Reached the top");
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        controller: _scrollController,
        child: Container(
          child: Text("This is some text that will be displayed in a scrollable view"),
        ),
      ),
    );
  }
}

相关问题