Flutter常用組件(Widget)解析-ListView


一個可滾動的列表組件

不管在哪,列表組件都尤為重要和常用。

首先來看個例子:

import 'package:flutter/material.dart';

void main () => runApp(MyApp());
class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return MaterialApp(
      title:'zengfp Flutter Demo',
      home:Scaffold(
        appBar:new AppBar(
          title:new Text('ListView Widget')
        ),
        body: ListView.builder(
          padding: EdgeInsets.all(8.0),
          itemExtent: 20.0,
          itemBuilder: (BuildContext context, int index) {
            return Text('entry $index');
          },
        )
      ),
    );
  }
}

 

當用戶滾動列表時,ListView中的數據將會無限增長。ListView類提供了一個builder屬性,itemBuilder值是一個匿名回調函數, 接受兩個參數- BuildContext和行迭代器i。迭代器從0開始, 每調用一次該函數,i就會自增1,對於每個建議的單詞對都會執行一次。該模型允許建議的單詞對列表在用戶滾動時無限增長。itemExtent是個double型,確定滾動區域中列表的數據長度。如果itemExtent確定,則會讓列表的渲染更為迅速和有效,讓性能體驗更好。

上面是個動態的列表,接下來看看固定列表:

body: ListView(
          padding: EdgeInsets.all(20.0),
          children: <Widget>[
            new Center(
              child: Text('first line'),
            ),
            new Center(
              child: Text('second line'),
            ),
            new Center(
              child: Text('third line'),
            ),
            new Center(
              child: Text('fourth line'),
            )
          ],
        )

 

上面則讓固定的四行文字居中顯示。

如果要水平方向的滾動,則需要使用到scrollDirection這個屬性了,比如:

body: Center(
          child: Container(
            height: 200.0,
            child: ListView(
              scrollDirection: Axis.horizontal,
              padding: EdgeInsets.all(20.0),
              children: <Widget>[
                new Container(
                    width: 200.0,
                    color: Colors.red,
                ),
                
                
                new Container(
                    width: 200.0,
                    color: Colors.green,
                ),
                
                new Container(
                    width: 200.0,
                    color: Colors.yellow,
                ),
              
                new Container(
                    width: 200.0,
                    color: Colors.black,
                
                )
              ],
            ),
          ),
        )

 

效果則是:

還有個reverse屬性,則是將列表的順序顛倒。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM