Skip to content

Calls to refresh() causes unwanted results #2

@BuyMyBeard

Description

@BuyMyBeard

Calling .refresh on the controller leads to unpredictable behavior. Most of the time, it leads to the ListView displaying no entries, but sometimes, will display one entry when one was added before the refresh was called.

The issue can be reproduced with this code sample:

import 'dart:math';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:example/database/firebase.dart';
import 'package:flutter/material.dart';
import 'package:firestore_paging_controller/firestore_paging_controller.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initFirebase();
  // fillDatabase();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  MyApp({super.key});

  // This controller will fetch user if it is either a male or older than 50
  final controller = FirestorePagingController.withoutType(
    basePath: 'users',
    pageSize: 10,
    orderBy: 'age',
    queryBuilders: [
      (query) => query.where('age', isGreaterThan: 20),
      (query) => query.where('gender', isEqualTo: 'male'),
    ],
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        floatingActionButton: FloatingActionButton(onPressed: _addUser, child: Icon(Icons.add)),
        body: PagedListView(
          pagingController: controller,
          builderDelegate: PagedChildBuilderDelegate<
              QueryDocumentSnapshot<Map<String, dynamic>>>(
            itemBuilder: (context, item, index) {
              return ListTile(
                title: Text(
                  'Age: ${item['age']} - Country: ${item['country']}',
                ),
                subtitle: Text('Gender: ${item['gender']}'),
              );
            },
          ),
        ),
      ),
    );
  }

  Future<void> _addUser() async {
    final random = Random();
    final user = {
      'age': random.nextInt(100),
      'gender': random.nextBool() ? 'male' : 'female',
      'country': countries[random.nextInt(countries.length)]
    };
    await FirebaseFirestore.instance.collection('users').add(user);
    controller.refresh();
  }
}

const countries = [
  "United States",
  "Canada",
  "Mexico",
  "Brazil",
  "United Kingdom",
  "Germany",
  "France",
  "Spain",
  "Italy",
  "Australia",
  "India",
  "China",
  "Japan",
  "South Korea",
  "Russia",
  "South Africa",
  "Egypt",
  "Nigeria",
  "Turkey",
  "Argentina"
];

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions