2017-04-19 159 views
5

我有一個可滾動的ListView,其中項目的數量可以動態更改。每當新項目添加到列表的末尾,我想以編程方式滾動ListView到最後。 (例如,類似的新郵件可以在結尾處添加聊天消息列表)以編程方式滾動到ListView的末尾

我的猜測是,我需要在我的State對象來創建ScrollController並手動將它傳遞給ListView構造函數,這樣我就可以稍後在控制器上調用animateTo()/jumpTo()方法。但是,由於我無法輕易確定最大滾動偏移量,因此似乎不可能簡單地執行scrollToEnd()類型的操作(但我可以輕鬆地通過0.0使其滾動到初始位置)。

有沒有簡單的方法來實現這一目標?

使用reverse: true對我來說不是一個完美的解決方案,因爲當只有少量的項目適合ListView視口時,我希望項目在頂部對齊。

回答

5

如果您使用帶有reverse: true的縮小包裝ListView,將其滾動到0.0將會按照您的要求進行。

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<MyHomePage> { 
    List<Widget> _messages = <Widget>[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, 
      curve: Curves.easeOut, 
      duration: const Duration(milliseconds: 300), 
     ); 
     } 
    ), 
    ); 
    } 
} 
+0

這個伎倆。在我的具體情況下,我不得不使用嵌套的列來將ListView放入擴展小部件中,但基本的想法是相同的。 – yyoon

+0

我來尋找一個解決方案,只是想提一下,其他答案可能是一個更好的方式來實現這一點 - https://stackoverflow.com/questions/44141148/how-to-get-full-size-of-一個滾動控制器 –

+1

我同意,那個答案(我也寫了)肯定更好。 –