flutter ScrollController滚动到底部的示例代码如下:

方式一:import 'package:flutter/scheduler.dart';

import 'package:flutter/material.dart';

void main() {

runApp(new MyApp());}class MyApp extends StatelessWidget {

@override  Widget build(BuildContext context) {

return new MaterialApp(

title: 'Flutter Demo',

home: new MyHomePage(),

);

}

}

class MyHomePage extends StatefulWidget {

State createState() => new MyHomePageState();}class MyHomePageState extends State {

ScrollController _scrollController = new ScrollController();

List _items = new List.generate(40, (index) {

return new Text("item $index");

});

@override  Widget build(BuildContext context) {

return new Scaffold(

floatingActionButton: new FloatingActionButton(

child: new Icon(Icons.arrow_downward),

onPressed: () {

setState(() {

_items.add(new Text("item ${_items.length}"));

});

SchedulerBinding.instance.addPostFrameCallback((_) { //build完成后的回调

_scrollController.animateTo(

_scrollController.position.maxScrollExtent,//滚动到底部

duration: const Duration(milliseconds: 300),

curve: Curves.easeOut,

);

});

},

),

body: new CustomScrollView(

controller: _scrollController,

slivers: [

new SliverAppBar(

title: new Text('Sliver App Bar'),

),

new SliverList(

delegate: new SliverChildBuilderDelegate(

(context, index) => _items[index],

childCount: _items.length,

),

),

],

),

);

}}

方式二:

还有另外一种实现方式,思路就是使用反向ListView。这样滚动到0,0位置的时候,由于是反向就是到了底部(这个也是类似聊天窗口常用的反向ListView),参考以下代码:import 'dart:collection';

import 'package:flutter/material.dart';

void main() {

runApp(new MyApp());}class MyApp extends StatelessWidget {

@override  Widget build(BuildContext context) {

return new MaterialApp(

title: 'Example',

home: new MyHomePage(),

);

}

}

class MyHomePage extends StatefulWidget {

@override

_MyHomePageState createState() => new _MyHomePageState();}class _MyHomePageState extends State {

List _messages = [new Text('hello'), new Text('world')];

ScrollController _scrollController = new ScrollController();

@override  Widget build(BuildContext context) {

return new Scaffold(

body: new Center(

child: new Container(

decoration: new BoxDecoration(backgroundColor: Colors.blueGrey.shade100),

width: 100.0,

height: 100.0,

child: new Column(

children: [

new Flexible(

child: new ListView(

controller: _scrollController,

reverse: true, //注意设置为反向

shrinkWrap: true,

children: new UnmodifiableListView(_messages),

),

),

],

),

),

),

floatingActionButton: new FloatingActionButton(

child: new Icon(Icons.add),

onPressed: () {

setState(() {

_messages.insert(0, new Text("message ${_messages.length}"));

});

_scrollController.animateTo(

0.0, //滚动到0,0就是底部(因为是反向的)

curve: Curves.easeOut,

duration: const Duration(milliseconds: 300),

);

}

),

);

}}

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐