如何使用ListView.builder顶部显示RefreshIndicator反向:true

时间:2018-07-23 13:09:07

标签: flutter flutter-layout flutter-animation

我正在构建一个简单的消息传递系统,用户将在其中看到消息列表。

我有一个带有reverse:true的ListView.Builder,因为我希望列表在加载消息页面时显示在底部。

当他们下拉以一直滚动到顶部时,我希望显示刷新指示器,以便他们可以加载以前的消息,就像大多数流行的聊天应用程序一样。

但是,由于在列表上具有reverse:true,因此他们必须在屏幕底部上拉才能使用RefreshIndicator加载先前的消息。

有没有一种方法可以使RefreshIndicator在下拉时触发而不是在使用reverse:true时触发?

1 个答案:

答案 0 :(得分:0)

在我看来,您是否想在列表视图的底部加载更多的内容,我认为您只需要在列表视图的最后一项添加一个加载更多的视图,就像下面的代码一样:

import 'package:flutter/material.dart';
import 'dart:async';


void main() {
  runApp(new MaterialApp(
    home: new Scaffold(
      body: new LoadMoreListView(enableLoadMore: true, count: 30,),
    ),
  ));
}

class LoadMoreListView extends StatefulWidget {

  bool enableLoadMore;
  int count;

  LoadMoreListView({this.enableLoadMore = true, this.count = 15});

  @override
  State<StatefulWidget> createState() {
    return new LoadMoreListViewState();
  }

}

class LoadMoreListViewState extends State<LoadMoreListView> {

  ScrollController _scrollController = new ScrollController();
  bool isRequesting = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        ///load more when the listView attached the bottom
        loadMore();
      }
    });
  }

  Future<Null> loadMore() async {
    if (isRequesting) {
      ///if is requesting ,return the next action
      return null;
    }
    setState(() {
      isRequesting = true;
    });

    ///loading your data from any where,eg:network
    return null;
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new ListView.builder(
        itemCount: _count(),
        itemBuilder: _buildItem);
  }

  _count() {
    if (widget.enableLoadMore) {
      return widget.count + 1;
    }
    return widget.count;
  }

  Widget _buildItem(BuildContext context, int index) {
    if (index == widget.count) {
      return _buildLoadMoreView();
    }
    return new Container(
      height: 36.0,
      child: new Center(
        child: new Text("I am the $index item"),
      ),
    );
  }

  Widget _buildLoadMoreView() {
    return new Padding(
      padding: const EdgeInsets.all(8.0),
      child: new Center(
        child: new Opacity(
          opacity: 1.0,
          child: new CircularProgressIndicator(),
        ),
      ),
    );
  }

}