Flutter可滾動(dòng)Widgets-ListView

個(gè)人博客

ListView

先看下如下截圖

enter image description here

以上效果圖的代碼,是從flutter官方demoflutter_gallery內(nèi)copy的部分代碼距芬。
首先涝开,首先定義一個(gè)列表,代碼如下

List<String> items = <String>[
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
];

然后框仔,通過(guò)上面的定義的列表數(shù)據(jù)舀武,現(xiàn)在構(gòu)建ListView的子Widget數(shù)據(jù),代碼如下

Iterable<Widget> listTiles = items
    .map<Widget>((String item) => buildListTile(context, item));

Widget buildListTile(BuildContext context, String item) {
    Widget secondary = const Text(
      'Even more additional list item information appears on line three.',
    );
    return ListTile(
      isThreeLine: true,
      leading: ExcludeSemantics(child: CircleAvatar(child: Text(item))),
      title: Text('This item represents $item.'),
      subtitle: secondary,
      trailing: Icon(Icons.info, color: Theme.of(context).disabledColor),
    );
}

最后离斩,將生成的子Widget數(shù)據(jù)填充到ListView內(nèi)银舱,代碼如下

ListView(
    children: listTiles.toList(),
)

以上代碼,就能完成最上面截圖的效果跛梗。下面主要對(duì)ListTile做一下介紹

ListTile

ListTileFlutter給我們準(zhǔn)備好的widget提供非常常見(jiàn)的構(gòu)造和定義方式寻馏,包括文字,icon核偿,點(diǎn)擊事件诚欠,一般是能夠滿(mǎn)足基本列表需求。

構(gòu)造函數(shù)

ListTile({
    Key key,
    this.leading,
    this.title,
    this.subtitle,
    this.trailing,
    this.isThreeLine = false,
    this.dense,
    this.contentPadding,
    this.enabled = true,
    this.onTap,
    this.onLongPress,
    this.selected = false,
 })

屬性

enter image description here

使用

ListTile(
    //展示三行
    isThreeLine: true,
    //前置圖標(biāo)
    leading: ExcludeSemantics(child: CircleAvatar(child: Text(item))),
    //標(biāo)題
    title: Text('This item represents $item.'),
    //副標(biāo)題
    subtitle: secondary,
    //后置圖標(biāo)
    trailing: Icon(Icons.info, color: Theme.of(context).disabledColor),
)

效果

enter image description here

ListView.builder

ListView.builder適合列表項(xiàng)比較多(或者無(wú)限)的情況宪祥,因?yàn)橹挥挟?dāng)子Widget真正顯示的時(shí)候才會(huì)被創(chuàng)建聂薪。
將上面列表填充的代碼修改為ListView.builder家乘,代碼如下所示

ListView.builder(
    itemCount: items.length,
    itemBuilder: (BuildContext context, int index) {
        return buildListTile(context, items[index]);
})

運(yùn)行結(jié)果如下圖所示


enter image description here

ListView.separated

ListView.separated可以生成列表項(xiàng)之間的分割器蝗羊,它比ListView.builder多了一個(gè)separatorBuilder參數(shù),該參數(shù)是一個(gè)分割器生成器仁锯。
將上面列表填充的代碼修改為ListView.separated耀找,代碼如下所示

ListView.separated(
    itemBuilder: (BuildContext context, int index) {
        return buildListTile(context, items[index]);
    },
    separatorBuilder: (BuildContext context, int index) {
        return index % 2 == 0 ? divider1 : divider2;
    },
    itemCount: items.length
)

運(yùn)行結(jié)果如下圖所示


enter image description here

實(shí)例:Listview下拉刷新 上拉加載更多

下面實(shí)現(xiàn)首次進(jìn)入頁(yè)面,加載數(shù)據(jù)业崖,下拉能刷新頁(yè)面數(shù)據(jù)野芒,上拉能加載更多數(shù)據(jù)。

下拉刷新

下拉刷新双炕,用到的是Flutter自帶的RefreshIndicatorWidget,ListView主要用ListView.builder進(jìn)行實(shí)現(xiàn)狞悲。代碼如下所示

RefreshIndicator(
    key: refreshIndicatorKey,
    child: ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, index) {
            return buildListTile(context, list[index]);
        },
    ),
    onRefresh: onRefresh)

實(shí)現(xiàn)下拉刷新,主要需要實(shí)現(xiàn)RefreshIndicatoronRefresh屬性妇斤,代碼如下所示

Future<Null> onRefresh() async {
    return Future.delayed(Duration(seconds: 2)).then((e) {
      list.addAll(items);
      setState(() {
        //重新構(gòu)建列表
      });
    });
}

主要實(shí)現(xiàn)延遲2s加載數(shù)據(jù)摇锋,在重新刷新列表丹拯。
首次進(jìn)入頁(yè)面,Loading狀態(tài)的實(shí)現(xiàn)實(shí)現(xiàn)如下面代碼所示

void showRefreshLoading() async {
    await Future.delayed(const Duration(seconds: 0), () {
      refreshIndicatorKey.currentState.show().then((e) {});
      return true;
    });
}

當(dāng)Loading完之后會(huì)觸發(fā)RefreshIndicatoronRefresh屬性荸恕,到此乖酬,下拉刷新已經(jīng)實(shí)現(xiàn)完畢。
運(yùn)行效果如下圖所示

enter image description here

上拉加載更多

上拉加載需要監(jiān)聽(tīng)ListView的滾動(dòng)事件融求,當(dāng)滾動(dòng)事件與底部小于50并且有更多數(shù)據(jù)加載時(shí)咬像,才會(huì)觸發(fā)加載更多的邏輯,如下面代碼所示

scrollController.addListener(() {
    var position = scrollController.position;
    // 小于50px時(shí)生宛,觸發(fā)上拉加載县昂;
    if (position.maxScrollExtent - position.pixels < 50 &&
        !isNoMore) {
        loadMore();
    }
});

void loadMore() async {
    if (!isLoading) {
      //刷新加載狀態(tài)
      isLoading = true;
      setState(() {});

      Future.delayed(Duration(seconds: 2)).then((e) {
        list.addAll(items);
        //取消加載狀態(tài),并提示暫無(wú)更多數(shù)據(jù)
        isLoading = false;
        isNoMore = true;
        setState(() {
          //重新構(gòu)建列表
        });
      });
    }
}

視圖層的代碼茅糜,當(dāng)需要處理加載更多的邏輯時(shí)七芭,ListViewitemCount屬性需要進(jìn)行加1,用來(lái)填充加載更多的視圖蔑赘。如下面代碼所示

int getListItemCount() {
    int count = list.length;
    if (isLoading || isNoMore) {
      count += 1;
    }
    return count;
}

ListViewitemBuilder屬性狸驳,加載更多的視圖代碼如下所示

Widget builderMore() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            isNoMore
                ? Text("")
                : SizedBox(
                    width: 20.0,
                    height: 20.0,
                    child: CircularProgressIndicator(
                        strokeWidth: 4.0,
                        valueColor: AlwaysStoppedAnimation(Colors.black)),
                  ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 15.0),
              child: Text(
                isNoMore ? "沒(méi)有更多數(shù)據(jù)" : "加載中...",
                style: TextStyle(fontSize: 16.0),
              ),
            ),
          ],
        ),
      ),
    );
  }

對(duì)RefreshIndicator代碼做如下修改

RefreshIndicator(
    key: refreshIndicatorKey,
    child: ListView.builder(
        controller: scrollController,
        itemCount: getListItemCount(),
        itemBuilder: (context, index) {
              return builderItem(context, index);
        },
    ),
    onRefresh: onRefresh)
          
Widget builderItem(BuildContext context, int index) {
    if (index < list.length) {
      return buildListTile(context, list[index]);
    }
    return builderMore();
}

運(yùn)行代碼
加載中的效果如下圖所示


enter image description here

沒(méi)有更多數(shù)據(jù)的效果如下圖所示


enter image description here
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市缩赛,隨后出現(xiàn)的幾起案子耙箍,更是在濱河造成了極大的恐慌,老刑警劉巖酥馍,帶你破解...
    沈念sama閱讀 217,185評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件辩昆,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡旨袒,警方通過(guò)查閱死者的電腦和手機(jī)汁针,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)砚尽,“玉大人施无,你說(shuō)我怎么就攤上這事”毓拢” “怎么了猾骡?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,524評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)敷搪。 經(jīng)常有香客問(wèn)我兴想,道長(zhǎng),這世上最難降的妖魔是什么赡勘? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,339評(píng)論 1 293
  • 正文 為了忘掉前任嫂便,我火速辦了婚禮,結(jié)果婚禮上闸与,老公的妹妹穿的比我還像新娘毙替。我一直安慰自己曼振,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,387評(píng)論 6 391
  • 文/花漫 我一把揭開(kāi)白布蔚龙。 她就那樣靜靜地躺著冰评,像睡著了一般。 火紅的嫁衣襯著肌膚如雪木羹。 梳的紋絲不亂的頭發(fā)上甲雅,一...
    開(kāi)封第一講書(shū)人閱讀 51,287評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音坑填,去河邊找鬼抛人。 笑死,一個(gè)胖子當(dāng)著我的面吹牛脐瑰,可吹牛的內(nèi)容都是我干的妖枚。 我是一名探鬼主播,決...
    沈念sama閱讀 40,130評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼苍在,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼绝页!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起寂恬,我...
    開(kāi)封第一講書(shū)人閱讀 38,985評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤续誉,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后初肉,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體酷鸦,經(jīng)...
    沈念sama閱讀 45,420評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,617評(píng)論 3 334
  • 正文 我和宋清朗相戀三年牙咏,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了臼隔。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,779評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡妄壶,死狀恐怖摔握,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情盯拱,我是刑警寧澤盒发,帶...
    沈念sama閱讀 35,477評(píng)論 5 345
  • 正文 年R本政府宣布例嘱,位于F島的核電站狡逢,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏拼卵。R本人自食惡果不足惜奢浑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,088評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望腋腮。 院中可真熱鬧雀彼,春花似錦壤蚜、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,716評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至莺丑,卻和暖如春著蟹,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背梢莽。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,857評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工萧豆, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人昏名。 一個(gè)月前我還...
    沈念sama閱讀 47,876評(píng)論 2 370
  • 正文 我出身青樓涮雷,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親轻局。 傳聞我的和親對(duì)象是個(gè)殘疾皇子洪鸭,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,700評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容