Flutter SingleChildScrollView代码控制滑动到底部或顶部

通过代码将SingleChildScrollView滑动到底部只需要两个步骤

  1. SingleChildScrollView设置一个ScrollController
  2. ScrollController调用jumpTo控制SingleChildScrollView互动到底部

如下实例代码,点击右下角FloatingActionButton将SingleChildScrollView滑动到底部

scrollController.position.maxScrollExtent获取的是底部的位置

同理,scrollController.position.minScrollExtent可以获取顶部位置

class _MyHomePageState extends State<MyHomePage> {

  ScrollController scrollController = ScrollController();

  void _scrollToend() {
    scrollController.jumpTo(scrollController.position.maxScrollExtent);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        controller: scrollController,
        child: Text('Hello World!\n'*100),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _scrollToend,
        tooltip: 'Scroll to end',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

 

posted @ 2019-10-30 15:22  野猿新一  阅读(222)  评论(0编辑  收藏  举报