微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Provider 向 Firebase Flutter 添加分页

如何解决使用 Provider 向 Firebase Flutter 添加分页

我有一个关于在 Flutter 应用程序中使用提供程序进行 Firebase 分页的问题。

这是我的问题我在提供者上有这个功能

  Future<void> fetchAndSetListings() async {
    QuerySnapshot snapshot;
    snapshot = await FirebaseFirestore.instance
        .collection('listings')
        .orderBy('price',descending: true)
        .limit(3)
        .get();

    lastDocument = snapshot.docs[snapshot.docs.length - 1];

    List<Listing> listingList = [];

    final user = FirebaseAuth.instance.currentUser;

    for (final document in snapshot.docs) {
      List<String> images = [];

      document.get('photos').forEach((photo) {
        images.add(photo);
      });

      bool favstat = await isItFav(user.uid,document.id);

      listingList.add(
        Listing(
          id: document.id,photos: images,price: double.parse(document.get('price').toString()),status: document.get('status'),street: document.get('street'),street2: document.get('street2'),city: document.get('city'),state: document.get('state'),zipCode: int.parse(document.get('zipCode').toString()),bedRooms: document.get('bedRooms'),bathRooms: document.get('bathRooms'),lotSize: document.get('lotSize'),schooldistric: document.get('schooldistric'),taxes: double.parse(document.get('taxes').toString()),homeFeatures: document.get('homeFeatures'),floorPlans: document.get('floorPlans'),propertySurvey: document.get('propertySurvey'),yearBuilt: document.get('yearBuilt'),listingAgentName: document.get('listingAgentName'),listingAgentEmail: document.get('listingAgentEmail'),listingAgentPhone: document.get('listingAgentPhone'),dayStore:
              DateTime.parse(document.get('dayStore').toDate().toString()),downPayment: document.get('downPayment'),county: document.get('county'),url: document.get('url'),listingType: document.get('listingType'),name: document.get('name'),username: document.get('username'),email: document.get('email'),imageUrl: document.get('image_url'),isFavorite: favstat,),);
    }
    _items.addAll(listingList);
    notifyListeners();
  }

还有这个其他功能

Future<void> fetchMore() async {
    QuerySnapshot snapshot;
    snapshot = await FirebaseFirestore.instance
        .collection('listings')
        .orderBy('price',descending: true)
        .startAfterDocument(lastDocument)
        .limit(3)
        .get();

    lastDocument = snapshot.docs[snapshot.docs.length - 1];

    List<Listing> listingList = [];

    final user = FirebaseAuth.instance.currentUser;

    for (final document in snapshot.docs) {
      List<String> images = [];

      document.get('photos').forEach((photo) {
        images.add(photo);
      });

      bool favstat = await isItFav(user.uid,);
    }
    _items.addAll(listingList);
    notifyListeners();
  }

在我的用户界面上,我有一个滚动控制器,它应该调用 get more:

import 'package:Flutter/material.dart';
import 'package:provider/provider.dart';

import '../providers/listings.dart';
import './listing_item.dart';

class ListingGrid extends StatefulWidget {
  final bool favorite;

  ListingGrid(this.favorite);

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

class _ListingGridState extends State<ListingGrid> {
  var _isLoading = false;
  ScrollController _scrollController;

  Future<void> _refeshListing(BuildContext context) async {
    await Provider.of<Listings>(context,listen: false).fetchAndSetListings();
  }

  @override
  void initState() {
    _scrollController = new ScrollController();
    _scrollController.addListener(() {
      double maxScroll = _scrollController.position.maxScrollExtent;
      double currentScroll = _scrollController.position.pixels;
      double delta = MediaQuery.of(context).size.height * 0.20;
      if (maxScroll - currentScroll <= delta) {
        Provider.of<Listings>(context,listen: false).fetchMore();
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final listingData = Provider.of<Listings>(context);
    final listingsWithFav =
        widget.favorite ? listingData.favoriteItems : listingData.items;
    final listings =
        listingsWithFav; //listingData.items; Esto si queres ver todos.

    return //GridView.builder(
        _isLoading
            ? Center(
                child: CircularProgressIndicator(),)
            : ListView.builder(
                controller: _scrollController,padding: const EdgeInsets.all(9.0),itemCount: listings.length,itemExtent: 300,itemBuilder: (ctx,i) => ChangeNotifierProvider.value(
                  value: listings[i],child: ListingItem(),);
  }
}

并且此代码从另一个屏幕激活,该屏幕具有在 Init 上请求的第一个函数

import 'package:Flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';

import '../widgets/listing_grid.dart';
import '../widgets/bottom_navigation_bar.dart';
import '../providers/listings.dart';

class ListingOverviewScreen extends StatefulWidget {
  static const routeName = '/listing-overview';

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

class _ListingOverviewScreenState extends State<ListingOverviewScreen>
    with SingleTickerProviderStateMixin {
  var _isLoading = false;
  var _isInit = true;

  @override
  void initState() {
    _tabController = TabController(length: 2,vsync: this);
    super.initState();
  }

  @override
  void didChangeDependencies() {
    if (_isInit) {
      setState(() {
        _isLoading = true;
      });
      Provider.of<Listings>(context).fetchAndSetListings().then((_) {
        setState(() {
          _isLoading = false;
        });
      });
    }
    _isInit = false;
    super.didChangeDependencies();
  }

  TabController _tabController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _isLoading
          ? Center(
              child: CircularProgressIndicator(),)
          : SafeArea(
              child: Column(
                children: [
                  Container(
                    color: Colors.grey[400],child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,children: [
                        Flexible(
                          child: TabBar(
                            isScrollable: true,labelColor: Colors.black,controller: _tabController,tabs: [
                              Tab(
                                text: 'New',Tab(
                                text: 'Likes',],Container(
                          padding: const EdgeInsets.all(10.0),child: Row(
                            children: [
                              GestureDetector(
                                onTap: () {
                                  print('Mapa Seleccionado');
                                },child: Text(
                                  'Maps',style: TextStyle(
                                    color: Colors.blue,fontWeight: FontWeight.bold,SizedBox(
                                width: 10,GestureDetector(
                                onTap: () {
                                  FirebaseAuth.instance.signOut();
                                  Navigator.of(context).pushNamed('/');
                                },child: Container(
                                  child: Row(
                                    children: [
                                      Icon(Icons.exit_to_app),SizedBox(
                                        width: 8,Expanded(
                    child: TabBarView(
                      children: [
                        ListingGrid(false),ListingGrid(true),bottomNavigationBar: BottomNavBar(0),);
  }
}

问题是数组获取了接下来的 3 个对象(列表)(目前 Firebase 中只有 10 个文档或列表)但随后它获取了无限数量的第二个 3 个列表,所以基本上我得到了文档 1,2, 3 在 init 和滚动时,我得到 4,5,6,但我得到的不是 7,8,9,而是一个 4,6 的永恒循环。

有什么想法吗?

亲切的问候。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。