Flutter入門進階之旅(十五)ListView下拉刷新&上拉加載更多

上期回顧

在上一篇博文中咱們在介紹ListView跟GridView的時候,限於篇幅問題咱們只講解了此兩者的簡單的使用方法,關於一些在實際開發中更經常使用的細節問咱們並無來得及跟你們展開講解,好比咱們在使用長列表的時的下拉刷新或者上拉加載更多的邏輯處理,今天的這篇文章咱們就來着重分析一下在flutter中咱們是若是實現長列表的下拉刷新跟上拉加載更多操做的。java

前言

現實開發中長列表佈局幾乎是全部APP的標配,幾乎你所使用的任何一款app都能找到長列表的身影,而長列表中必不可少的操做確定是下拉刷新、上拉加載更多。在原生Android中咱們通常使用RecyclerView配合support.v4包下面的SwipeRefreshLayout來完成下拉刷新動做,經過給RecyclerView綁定RecyclerView.OnScrollListener()拖動監聽事件來判斷列表的滑動狀態來決定是否進行加載更多的操做,有了原生Android開發的經驗,咱們徹底能夠把這個思路一樣應用在Flutter中的長列表操做上。下面咱們一塊兒來看下Flutter中的下拉刷新跟上拉加載更多吧。app

1.下拉刷新

Flutter跟Android做爲Google的親兒子不管是在在風格命名仍是設計思路上都有很大的類似跟想通性,上一篇博文中咱們提到Flutter中使用ListViiew跟GridView來完成長列表佈局,跟原生Android命名都同樣,在Flutter中給咱們提供的RefreshIndicator組件跟原生Android中的SwipeRefreshLayout設計思路同樣,都是爲了簡化咱們完成下拉刷新的監聽動做。並且RefreshIndicator跟原生Android的SwipeRefreshLayout在外觀上幾乎也同樣,都遵循了google material design設計理念。less

/// Creates a refresh indicator.
  ///
  /// The [onRefresh], [child], and [notificationPredicate] arguments must be
  /// non-null. The default
  /// [displacement] is 40.0 logical pixels.
  ///
  /// The [semanticsLabel] is used to specify an accessibility label for this widget.
  /// If it is null, it will be defaulted to [MaterialLocalizations.refreshIndicatorSemanticLabel].
  /// An empty string may be passed to avoid having anything read by screen reading software.
  /// The [semanticsValue] may be used to specify progress on the widget. The
  const RefreshIndicator({ Key key, @required this.child, this.displacement = 40.0, //圓環進度條展現居頂部的位置 @required this.onRefresh, //刷新回調 this.color, //圓環進度條顏色 this.backgroundColor, //背景顏色 this.notificationPredicate = defaultScrollNotificationPredicate, this.semanticsLabel, this.semanticsValue, }) 複製代碼

在上面的構造方法中必要參數我都給了詳細的註釋說明,因此這裏我就很少展開講解了,先來看一張下拉刷新的效果圖,稍後結合代碼我再作具體講解。async

效果圖 ide

在這裏插入圖片描述

樣例代碼函數

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    title: "ListView",
    debugShowCheckedModeBanner: false,
    home: new MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State {
  List<ItemEntity> entityList = [];

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 10; i++) {
      entityList.add(ItemEntity("Item $i", Icons.accessibility));
    }
  }

  Future<Null> _handleRefresh() async {
    print('-------開始刷新------------');
    await Future.delayed(Duration(seconds: 2), () {
      //模擬延時
      setState(() {
        entityList.clear();
        entityList = List.generate(
            10,
            (index) =>
                new ItemEntity("下拉刷新後--item $index", Icons.accessibility));
        return null;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("ListView"),
        ),
        body: RefreshIndicator(
            displacement: 50,
            color: Colors.redAccent,
            backgroundColor: Colors.blue,
            child: ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                return ItemView(entityList[index]);
              },
              itemCount: entityList.length,
            ),
            onRefresh: _handleRefresh));
  }
}

/** * 渲染Item的實體類 */
class ItemEntity {
  String title;
  IconData iconData;

  ItemEntity(this.title, this.iconData);
}

/** * ListView builder生成的Item佈局,讀者可類比成原生Android的Adapter的角色 */
class ItemView extends StatelessWidget {
  ItemEntity itemEntity;

  ItemView(this.itemEntity);

  @override
  Widget build(BuildContext context) {
    return Container(
        height: 100,
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            Text(
              itemEntity.title,
              style: TextStyle(color: Colors.black87),
            ),
            Positioned(
                child: Icon(
                  itemEntity.iconData,
                  size: 30,
                  color: Colors.blue,
                ),
                left: 5)
          ],
        ));
  }
}
複製代碼

上述代碼我仍是藉助上篇博文中講解ListView的例子,只不過ListView的外層用RefreshIndicator包裹了一下,而且給RefreshIndicatoronRefresh綁定了處理下拉刷新事件的回調函數。佈局

Future<Null> _handleRefresh() async {
    print('-------開始刷新------------');
    await Future.delayed(Duration(seconds: 2), () {
      //模擬延時
      setState(() {
        entityList.clear();
        entityList = List.generate(
            10,
            (index) =>
                new ItemEntity("下拉刷新後--item $index", Icons.accessibility));
        return null;
      });
    });
  }
複製代碼

在_handleRefresh()中,咱們經過Future.delayed模擬延時操做,在延時函數執行完畢以後,首先清空咱們在initState中模擬的列表數據,而後從新生成刷新後的數據,經過setState從新渲染ListView上綁定的數據來完成下拉刷下這一操做。測試

2.上拉加載更多

繼續完善下拉刷新的代碼,咱們藉助ScrollController給ListView添加滑動監聽事件ui

ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                if (index == entityList.length) {
                  return LoadMoreView();
                } else {
                  return ItemView(entityList[index]);
                }
              },
              itemCount: entityList.length + 1,
              controller: _scrollController,
            ),
            onRefresh: _handleRefresh));
複製代碼

而後經過_scrollController監聽手指上下拖動時在屏幕上產生的滾動距離來判斷是否觸發加載更多的操做this

_scrollController.addListener(() {
      if (_scrollController.position.pixels ==_scrollController.position.maxScrollExtent) {
        print("------------加載更多-------------");
        _getMoreData();
      }
    });
複製代碼

咱們藉助ScrollController來判斷當前ListView可拖動的距離是否等於listview的最大可拖動距離,若是等於,那麼就會觸發加載更多的操做,而後咱們去作相應的邏輯從而完成加載更多的操做。

其實如今講完Flutter中下拉刷新跟加載更多的操做,你會發如今Flutter中處理這些操做跟開篇提到的原生Android的處理方式跟思想幾乎是一致的,咱們來看下完成下拉刷新跟加載更多後的完整效果圖。

效果圖

加載更多
先來看下總體代碼,稍後我在結合代碼講解一下這裏須要注意的一個小細節。

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    title: "ListView",
    debugShowCheckedModeBanner: false,
    home: new MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State {
  List<ItemEntity> entityList = [];
  ScrollController _scrollController = new ScrollController();
  bool isLoadData = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        print("------------加載更多-------------");
        _getMoreData();
      }
    });
    for (int i = 0; i < 10; i++) {
      entityList.add(ItemEntity("Item $i", Icons.accessibility));
    }
  }

  Future<Null> _getMoreData() async {
    await Future.delayed(Duration(seconds: 2), () { //模擬延時操做
      if (!isLoadData) {
        isLoadData = true;
        setState(() {
          isLoadData = false;
          List<ItemEntity> newList = List.generate(5, (index) =>
          new ItemEntity(
              "上拉加載--item ${index + entityList.length}", Icons.accessibility));
          entityList.addAll(newList);
        });
      }
    });
  }

  Future<Null> _handleRefresh() async {
    print('-------開始刷新------------');
    await Future.delayed(Duration(seconds: 2), () { //模擬延時
      setState(() {
        entityList.clear();
        entityList = List.generate(10,
                (index) =>
            new ItemEntity("下拉刷新後--item $index", Icons.accessibility));
        return null;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("ListView"),
        ),
        body: RefreshIndicator(
            displacement: 50,
            color: Colors.redAccent,
            backgroundColor: Colors.blue,
            child: ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                if (index == entityList.length) {
                  return LoadMoreView();
                } else {
                  return ItemView(entityList[index]);
                }
              },
              itemCount: entityList.length + 1,
              controller: _scrollController,
            ),
            onRefresh: _handleRefresh));
  }
}

/** * 渲染Item的實體類 */
class ItemEntity {
  String title;
  IconData iconData;

  ItemEntity(this.title, this.iconData);
}

/** * ListView builder生成的Item佈局,讀者可類比成原生Android的Adapter的角色 */
class ItemView extends StatelessWidget {
  ItemEntity itemEntity;

  ItemView(this.itemEntity);

  @override
  Widget build(BuildContext context) {
    return Container(
        height: 100,
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            Text(
              itemEntity.title,
              style: TextStyle(color: Colors.black87),
            ),
            Positioned(
                child: Icon(
                  itemEntity.iconData,
                  size: 30,
                  color: Colors.blue,
                ),
                left: 5)
          ],
        ));
  }
}

class LoadMoreView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(child: Padding(
      padding: const EdgeInsets.all(18.0),
      child: Center(
        child: Row(children: <Widget>[
          new CircularProgressIndicator(),
          Padding(padding: EdgeInsets.all(10)),
          Text('加載中...')
        ], mainAxisAlignment: MainAxisAlignment.center,),
      ),
    ), color: Colors.white70,);
  }

}
複製代碼

上述代碼中關於listView的itemBuilder的部分代碼我作下簡單的解釋說明:

ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                if (index == entityList.length) { //是否滑動到底部
                  return LoadMoreView();
                } else {
                  return ItemView(entityList[index]);
                }
              },
              itemCount: entityList.length + 1,
              controller: _scrollController,
            ),
            
複製代碼

對比一開始下拉刷新的代碼,細心的讀者可能注意到,加載更多邏輯處理是在itemBuilder的時候多了一個邏輯判斷

if (當前Item的角標==數據集合的長度) {  //滑動到最底部的時候
        顯示加載更多的佈局  LoadMoreView();
   }else{
       顯示正常的Item佈局  ItemView();
   }

複製代碼

而後就是itemCount的數量天然也要加1,itemCount: entityList.length + 1加的這個1就是最底部的LoadMoreView的佈局。關於_scrollController所觸發的回調函數我就很少作講解了,跟處理下拉刷新時的邏輯代碼同樣,讀者可結合上述完整代碼自行對比理解。

好了,至此關於ListView的上拉加載更多跟下拉刷新操做我就爲你們講解完畢了,至於GridView的上下拉操做跟listView原理同樣,我就不在此過多廢話了,讀者可自行寫代碼測試GridView的上下拉刷新操做。

相關文章
相關標籤/搜索