美文网首页
flutter 滚动监听

flutter 滚动监听

作者: CaptainRoy | 来源:发表于2019-10-12 09:41 被阅读0次
    ScrollController
    ScrollController
    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return MaterialApp(
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      @override
      State<StatefulWidget> createState() {
        // TODO: implement createState
        return MyHomePageState();
      }
    }
    
    class MyHomePageState extends State<MyHomePage> {
      ScrollController scrollController;
      bool isShowTop = false;
    
      @override
      void initState() {
        // 初始化ScrollController
        scrollController = ScrollController();
    
        // 监听滚动
        scrollController.addListener(() {
          var tempShowTop = scrollController.offset >= 1000;
          if (tempShowTop != isShowTop) {
            setState(() {
              isShowTop = tempShowTop;
            });
          }
        });
    
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return Scaffold(
          appBar: AppBar(
            title: Text("ListView展示"),
          ),
          body: ListView.builder(
            itemCount: 1000,
            itemExtent: 60,
            controller: scrollController,
            itemBuilder: (BuildContext context, int index) {
              return ListTile(
                title: Text("Item$index"),
              );
            },
          ),
          floatingActionButton: !isShowTop
              ? null
              : FloatingActionButton(
                  child: Icon(Icons.arrow_upward),
                  onPressed: () {
                    scrollController.animateTo(0,
                        duration: Duration(milliseconds: 1000), curve: Curves.ease);
                  },
                ),
        );
      }
    }
    

    相关文章

      网友评论

          本文标题:flutter 滚动监听

          本文链接:https://www.haomeiwen.com/subject/nigfmctx.html