使用Firebase实时数据库在Flutter中进行分页

时间:2019-01-31 16:20:12

标签: firebase firebase-realtime-database pagination flutter

我正在尝试使用Firebase实时数据库在Flutter中进行分页。 我已经在Firestore中尝试过此方法,并且在那里可以正常工作,但我希望将其与实时数据库一起使用。

我是第一次这样获取数据。

 Widget buildListMessage() {
    return Flexible(
      child: StreamBuilder(
        stream: _firebase.firebaseDB
            .reference()
            .child("chats")
            .child("nsbcalculator")
            .orderByChild('timestamp')
            .limitToFirst(15)
            .onValue,
        builder: (context, AsyncSnapshot<Event> snapshot) {
          if (!snapshot.hasData) {
            return Center(
                child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(themeColor)));
          } else {

            if (snapshot.data.snapshot.value != null) {

                listMessage = Map.from(snapshot.data.snapshot.value)
                    .values
                    .toList()
                      ..sort(
                          (a, b) => a['timestamp'].compareTo(b['timestamp']));

              if (lastVisible == null) {
                lastVisible = listMessage.last;
                listMessage.removeLast();
              }
            }

            return ListView.builder(
              ...
            );
          }
        },
      ),
    );
  }

在此之后,我要使用ScrollController监听器

  void _scrollListener() async {
    if (listScrollController.position.pixels ==
        listScrollController.position.maxScrollExtent) {
      _fetchMore();
    }
  }

最后

  _fetchMore() {
    _firebase.firebaseDB
        .reference()
        .child("chats")
        .child("nsbcalculator")
        .orderByChild('timestamp')
        .startAt(lastVisible['timestamp'])
        .limitToFirst(5)
        .once()
        .then((snapshot) {

      List snapList = Map.from(snapshot.value).values.toList()
        ..sort((a, b) => a['timestamp'].compareTo(b['timestamp']));


      if (snapList.isNotEmpty) {
        print(snapList.length.toString());

        if (!noMore) {

          listMessage.removeLast();

          //Problem is here.....??
          setState(() {
            listMessage..addAll(snapList);
          });

          lastVisible = snapList.last;

          print(lastVisible['content']);
        }

        if (snapList.length < 5) {
          noMore = true;
        }
      }
    });
  }

它可以像实时通信一样正常工作,但是当我尝试在_fetchMore()中进行分页时,会调用setState,但它会刷新整个小部件的状态并再次重新启动StreamBuilder,并且所有数据都仅由新查询替换。我该如何预防呢?

2 个答案:

答案 0 :(得分:2)

调用setState将重绘整个窗口小部件和列表视图。现在,由于您提供的是第一页的蒸汽,因此在重绘后仅加载它。为避免这种情况,您可以使用自己的流并为其提供新的内容。然后您的StreamBuilder将自动处理更新。

您需要将项目的完整列表存储为单独的变量,对其进行更新,然后沉入流中。

final _list = List<Event>();
final _listController = StreamController<List<Event>>.broadcast();
Stream<List<Event>> get listStream => _listController.stream;

@override
void initState() {
  super.initState();
  // Here you need to load your first page and then add to your stream
  ...
  _list.addAll(firstPageItems);
  _listController.sink.add(_list);
}

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

Widget buildListMessage() {
    return Flexible(
      child: StreamBuilder(
        stream: listStream
        ...
}

_fetchMore() {
  ...
  // Do your fetch and then just add items to the stream
  _list.addAll(snapList);
  _listController.sink.add(_list);
  ...
}

答案 1 :(得分:0)

试试这个
实时列表分页

class FireStoreRepository {
  final CollectionReference _chatCollectionReference =
      Firestore.instance.collection('Chat');

  final StreamController<List<ChatModel>> _chatController =
      StreamController<List<ChatModel>>.broadcast();

  List<List<ChatModel>> _allPagedResults = List<List<ChatModel>>();

  static const int chatLimit = 10;
  DocumentSnapshot _lastDocument;
  bool _hasMoreData = true;

  Stream listenToChatsRealTime() {
    _requestChats();
    return _chatController.stream;
  }

  void _requestChats() {
    var pagechatQuery = _chatCollectionReference
        .orderBy('timestamp', descending: true)
        .limit(chatLimit);

    if (_lastDocument != null) {
      pagechatQuery =
          pagechatQuery.startAfterDocument(_lastDocument);
    }

    if (!_hasMoreData) return;

    var currentRequestIndex = _allPagedResults.length;

    pagechatQuery.snapshots().listen(
      (snapshot) {
        if (snapshot.documents.isNotEmpty) {
          var generalChats = snapshot.documents
              .map((snapshot) => ChatModel.fromMap(snapshot.data))
              .toList();

          var pageExists = currentRequestIndex < _allPagedResults.length;

          if (pageExists) {
            _allPagedResults[currentRequestIndex] = generalChats;
          } else {
            _allPagedResults.add(generalChats);
          }

          var allChats = _allPagedResults.fold<List<ChatModel>>(
              List<ChatModel>(),
              (initialValue, pageItems) => initialValue..addAll(pageItems));

          _chatController.add(allChats);

          if (currentRequestIndex == _allPagedResults.length - 1) {
            _lastDocument = snapshot.documents.last;
          }

          _hasMoreData = generalChats.length == chatLimit;
        }
      },
    );
  }

  void requestMoreData() => _requestChats();
}

ChatListView

class ChatView extends StatefulWidget {
  ChatView({Key key}) : super(key: key);

  @override
  _ChatViewState createState() => _ChatViewState();
}

class _ChatViewState extends State<ChatView> {

FireStoreRepository _fireStoreRepository;
final ScrollController _listScrollController = new ScrollController();

@override
  void initState() {
    super.initState();
    _fireStoreRepository = FireStoreRepository();
    _listScrollController.addListener(_scrollListener);
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Flexible(
        child: StreamBuilder<List<ChatModel>>(
          stream: _fireStoreRepository.listenToChatsRealTime(),
          builder: (context, snapshot) {
             return ListView.builder(
              itemCount: snapshot.data.length,
              controller: _listScrollController,
              shrinkWrap: true,
              reverse: true,
              itemBuilder: (context, index) {
                ...
              }
            );
          }
        )
      ),
    );
  }

  void _scrollListener() {
    if (_listScrollController.offset >=
            _listScrollController.position.maxScrollExtent &&
        !_listScrollController.position.outOfRange) {
      _fireStoreRepository.requestMoreData();
    }
  }

}

ChatModel类

class ChatModel {
  final String userID;
  final String message;
  final DateTime timeStamp;

  ChatModel({this.userID, this.message, this.timeStamp});

  //send 
  Map<String, dynamic> toMap() {
    return {
      'userid': userID,
      'message': message,
      'timestamp': timeStamp,
    };
  }

  //fetch
  static ChatModel fromMap(Map<String, dynamic> map) {
    if (map == null) return null;

    return ChatModel(
      userID: map['userid'],
      message: map['message'],
      timeStamp: DateTime.fromMicrosecondsSinceEpoch(map['timestamp'] * 1000),
    );
  }
}