forked from firebase/FirebaseUI-Flutter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_builder.dart
More file actions
743 lines (663 loc) · 23.7 KB
/
query_builder.dart
File metadata and controls
743 lines (663 loc) · 23.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
// Copyright 2022, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:firebase_ui_shared/firebase_ui_shared.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
/// A function that builds a widget from a [FirestoreQueryBuilderSnapshot]
///
/// See also [FirebaseDatabaseQueryBuilder].
typedef FirestoreQueryBuilderSnapshotBuilder<T> = Widget Function(
BuildContext context,
FirestoreQueryBuilderSnapshot<T> snapshot,
Widget? child,
);
/// {@template firebase_ui.firestore_query_builder}
/// Listens to a query and paginates the result in a way that is compatible with
/// infinite scroll views, such as [ListView] or [GridView].
///
/// [FirestoreQueryBuilder] will subscribe to the query and obtain the first
/// [pageSize] items (10 by default). Then as the UI needs to render more items,
/// it is possible to call [FirestoreQueryBuilderSnapshot.fetchMore] to obtain more items.
///
/// [FirestoreQueryBuilder] is independent from how the query will be rendered
/// and as such can be used with any existing widget for rendering list of items.
///
/// An example of how to combine [FirestoreQueryBuilder] with [ListView] would be:
///
/// ```dart
/// FirestoreQueryBuilder<Movie>(
/// query: moviesCollection.orderBy('title'),
/// builder: (context, snapshot, _) {
/// if (snapshot.isFetching) {
/// return const CircularProgressIndicator();
/// }
/// if (snapshot.hasError) {
/// return Text('error ${snapshot.error}');
/// }
///
/// return ListView.builder(
/// itemCount: snapshot.docs.length,
/// itemBuilder: (context, index) {
/// // if we reached the end of the currently obtained items, we try to
/// // obtain more items
/// if (snapshot.hasMore && index + 1 == snapshot.docs.length) {
/// // Tell FirestoreQueryBuilder to try to obtain more items.
/// // It is safe to call this function from within the build method.
/// snapshot.fetchMore();
/// }
///
/// final movie = snapshot.docs[index];
/// return Text(movie.title);
/// },
/// );
/// },
/// )
/// ```
/// {@endtemplate}
/// {@subCategory service:firestore}
/// {@subCategory type:widget}
/// {@subCategory description:A widget that listens to a query.}
/// {@subCategory img:https://place-hold.it/400x150}
class FirestoreQueryBuilder<Document> extends StatefulWidget {
/// {@macro firebase_ui.firestore_query_builder}
const FirestoreQueryBuilder({
super.key,
required this.query,
required this.builder,
this.pageSize = 10,
this.includeMetadataChanges = false,
this.child,
}) : assert(pageSize > 1, 'Cannot have a pageSize lower than 1');
/// The query that will be paginated.
///
/// When the query changes, the pagination will restart from first page.
final Query<Document> query;
/// The number of items that will be fetched at a time.
///
/// When it changes, the current progress will be preserved.
final int pageSize;
/// Whether to include metadata changes in the query.
/// Defaults to false.
final bool includeMetadataChanges;
final FirestoreQueryBuilderSnapshotBuilder<Document> builder;
/// A widget that will be passed to [builder] for optimizations purpose.
///
/// Since this widget is not created within [builder], it won't rebuild
/// when the query emits an update.
final Widget? child;
@override
// ignore: library_private_types_in_public_api
_FirestoreQueryBuilderState<Document> createState() =>
_FirestoreQueryBuilderState<Document>();
}
class _FirestoreQueryBuilderState<Document>
extends State<FirestoreQueryBuilder<Document>> {
StreamSubscription? _querySubscription;
var _pageCount = 0;
late var _snapshot = _QueryBuilderSnapshot<Document>._(
docs: [],
error: null,
hasData: false,
hasError: false,
hasMore: false,
isFetching: false,
isFetchingMore: false,
stackTrace: null,
fetchMore: _fetchNextPage,
);
void _fetchNextPage() {
if (_snapshot.isFetching ||
!_snapshot.hasMore ||
_snapshot.isFetchingMore) {
return;
}
_pageCount++;
_listenQuery(nextPage: true);
}
@override
void initState() {
super.initState();
_listenQuery();
}
@override
void didUpdateWidget(FirestoreQueryBuilder<Document> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.query != widget.query) {
_pageCount = 0;
_listenQuery();
} else if (oldWidget.pageSize != widget.pageSize) {
// The page size changes, so we re-fetch items, making sure we're
// preserving the current progress.
final previousItemCount = (oldWidget.pageSize + 1) * _pageCount;
_pageCount = (previousItemCount / widget.pageSize).ceil();
_listenQuery();
}
}
void _listenQuery({bool nextPage = false}) {
_querySubscription?.cancel();
if (nextPage) {
_snapshot = _snapshot.copyWith(isFetchingMore: true);
} else {
_snapshot = _snapshot.copyWith(isFetching: true);
}
// Delaying the setState so that fetchNextpage can be used within a child's
// "build" – most commonly ListView's itemBuilder
Future.microtask(() => setState(() {}));
final expectedDocsCount = (_pageCount + 1) * widget.pageSize
/// The "+1" is used to voluntarily fetch one extra item,
/// used to determine whether there is a next page or not.
/// This extra item will not be rendered.
+
1;
final query = widget.query.limit(expectedDocsCount);
_querySubscription = query
.snapshots(includeMetadataChanges: widget.includeMetadataChanges)
.listen(
(event) {
setState(() {
if (nextPage) {
_snapshot = _snapshot.copyWith(isFetchingMore: false);
} else {
_snapshot = _snapshot.copyWith(isFetching: false);
}
_snapshot = _snapshot.copyWith(
hasData: true,
docs: event.size < expectedDocsCount
? event.docs
: event.docs.take(expectedDocsCount - 1).toList(),
error: null,
hasMore: event.size == expectedDocsCount,
stackTrace: null,
hasError: false,
);
});
},
onError: (Object error, StackTrace stackTrace) {
setState(() {
if (nextPage) {
_snapshot = _snapshot.copyWith(isFetchingMore: false);
} else {
_snapshot = _snapshot.copyWith(isFetching: false);
}
_snapshot = _snapshot.copyWith(
error: error,
stackTrace: stackTrace,
hasError: true,
hasMore: false,
);
});
},
);
}
@override
void dispose() {
_querySubscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return widget.builder(context, _snapshot, widget.child);
}
}
/// The result of a paginated query.
abstract class FirestoreQueryBuilderSnapshot<Document> {
/// Whether the first page of the query is currently being fetched.
///
/// [isFetching] will reset to `true` when the query changes, in which case
/// a widget can have both [isFetching] as `true` and [hasData]/[hasError] as
/// `true.
bool get isFetching;
/// Whether a new page is being fetched.
///
/// See also [fetchMore].
bool get isFetchingMore;
/// Whether a page was not obtained.
///
/// On error, [docs] will still be available if a valid result was emitted
/// previously.
bool get hasError;
/// Whether at least one page was obtained.
///
/// It is possible for [hasData] to be `true` and [hasError]/[isFetching]
/// to also be true. That is because [docs] will still be available even
/// when the query changed or an error was emitted.
bool get hasData;
/// Whether there is an extra page to fetch
///
/// See also [fetchMore].
bool get hasMore;
/// The error emitted, if any.
Object? get error;
/// If an error was emitted, the stackTrace associated to this error.
StackTrace? get stackTrace;
/// All the items obtained.
List<QueryDocumentSnapshot<Document>> get docs;
/// Try to obtain more items from the collection.
///
/// It is safe to call this method multiple times at once or to call it
/// within the `build` method of a widget.
void fetchMore();
}
class _QueryBuilderSnapshot<Document>
implements FirestoreQueryBuilderSnapshot<Document> {
_QueryBuilderSnapshot._({
required this.docs,
required this.error,
required this.hasData,
required this.hasError,
required this.isFetching,
required this.isFetchingMore,
required this.stackTrace,
required this.hasMore,
required VoidCallback fetchMore,
}) : _fetchNextPage = fetchMore;
@override
final List<QueryDocumentSnapshot<Document>> docs;
@override
final Object? error;
@override
final bool hasData;
@override
final bool hasError;
@override
final bool hasMore;
@override
final bool isFetching;
@override
final bool isFetchingMore;
@override
final StackTrace? stackTrace;
final VoidCallback _fetchNextPage;
@override
void fetchMore() => _fetchNextPage();
_QueryBuilderSnapshot<Document> copyWith({
Object? docs = const _Sentinel(),
Object? error = const _Sentinel(),
Object? hasData = const _Sentinel(),
Object? hasError = const _Sentinel(),
Object? hasMore = const _Sentinel(),
Object? isFetching = const _Sentinel(),
Object? isFetchingMore = const _Sentinel(),
Object? stackTrace = const _Sentinel(),
}) {
T valueAs<T>(Object? maybeNewValue, T previousValue) {
if (maybeNewValue == const _Sentinel()) {
return previousValue;
}
return maybeNewValue as T;
}
return _QueryBuilderSnapshot._(
docs: valueAs(docs, this.docs),
error: valueAs(error, this.error),
hasData: valueAs(hasData, this.hasData),
hasMore: valueAs(hasMore, this.hasMore),
hasError: valueAs(hasError, this.hasError),
isFetching: valueAs(isFetching, this.isFetching),
isFetchingMore: valueAs(isFetchingMore, this.isFetchingMore),
stackTrace: valueAs(stackTrace, this.stackTrace),
fetchMore: fetchMore,
);
}
}
class _Sentinel {
const _Sentinel();
}
/// A type representing the function passed to [FirestoreListView] for its `itemBuilder`.
typedef FirestoreItemBuilder<Document> = Widget Function(
BuildContext context,
QueryDocumentSnapshot<Document> doc,
);
/// A type representing the function passed to [FirestoreListView] for its `loadingBuilder`.
typedef FirestoreLoadingBuilder = Widget Function(BuildContext context);
/// A type representing the function passed to [FirestoreListView] for its `loadingIndicatorBuilder`.
typedef FirestoreFetchingIndicatorBuilder = Widget Function(
BuildContext context,
);
/// A type representing the function passed to [FirestoreListView] for its `errorBuilder`.
typedef FirestoreErrorBuilder = Widget Function(
BuildContext context,
Object error,
StackTrace stackTrace,
);
/// A type representing the function passed to [FirestoreListView] for its `emptyBuilder`.
typedef FirestoreEmptyBuilder = Widget Function(BuildContext context);
/// {@template firebase_ui.firestorelistview}
/// A [ListView.builder] that obtains its items from a Firestore query.
///
/// As an example, consider the following collection:
///
/// ```dart
/// class Movie {
/// Movie({required this.title, required this.genre});
///
/// Movie.fromJson(Map<String, Object?> json)
/// : this(
/// title: json['title']! as String,
/// genre: json['genre']! as String,
/// );
///
/// final String title;
/// final String genre;
///
/// Map<String, Object?> toJson() {
/// return {
/// 'title': title,
/// 'genre': genre,
/// };
/// }
/// }
///
/// final moviesCollection = FirebaseFirestore.instance.collection('movies').withConverter<Movie>(
/// fromFirestore: (snapshot, _) => Movie.fromJson(snapshot.data()!),
/// toFirestore: (movie, _) => movie.toJson(),
/// );
/// ```
///
///
/// Using [FirestoreListView], we can now show the list of movies by writing:
///
/// ```dart
/// FirestoreListView<Movie>(
/// query: moviesCollection.orderBy('title'),
/// itemBuilder: (context, snapshot) {
/// Movie movie = snapshot.data();
/// return Text(movie.title);
/// },
/// )
/// ```
///
/// For advanced UI use-cases, consider switching to [FirestoreQueryBuilder].
/// {@endtemplate}
/// {@subCategory service:firestore}
/// {@subCategory type:widget}
/// {@subCategory description:A widget that listens to a query and display the items using a ListView}
/// {@subCategory img:https://place-hold.it/400x150}
class FirestoreListView<Document> extends FirestoreQueryBuilder<Document> {
/// {@macro firebase_ui.firestorelistview}
FirestoreListView({
super.key,
required super.query,
required FirestoreItemBuilder<Document> itemBuilder,
super.pageSize,
super.includeMetadataChanges,
FirestoreLoadingBuilder? loadingBuilder,
FirestoreFetchingIndicatorBuilder? fetchingIndicatorBuilder,
FirestoreErrorBuilder? errorBuilder,
FirestoreEmptyBuilder? emptyBuilder,
Axis scrollDirection = Axis.vertical,
bool showFetchingIndicator = false,
bool reverse = false,
ScrollController? controller,
bool? primary,
ScrollPhysics? physics,
bool shrinkWrap = false,
EdgeInsetsGeometry? padding,
double? itemExtent,
Widget? prototypeItem,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
double? cacheExtent,
int? semanticChildCount,
DragStartBehavior dragStartBehavior = DragStartBehavior.start,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior =
ScrollViewKeyboardDismissBehavior.manual,
String? restorationId,
Clip clipBehavior = Clip.hardEdge,
}) : super(
builder: (context, snapshot, _) {
if (snapshot.isFetching) {
return loadingBuilder?.call(context) ??
const Center(child: CircularProgressIndicator.adaptive());
}
if (snapshot.hasError && errorBuilder != null) {
return errorBuilder(
context,
snapshot.error!,
snapshot.stackTrace!,
);
}
if (snapshot.docs.isEmpty && emptyBuilder != null) {
return emptyBuilder(context);
}
final itemCount = snapshot.docs.length;
return ListView.builder(
itemCount: itemCount,
itemBuilder: (context, index) {
final isLastItem = index + 1 == itemCount;
if (!showFetchingIndicator && isLastItem && snapshot.hasMore) {
snapshot.fetchMore();
}
final doc = snapshot.docs[index];
return showFetchingIndicator
? OnMountListener(
onMount: () {
if (isLastItem && snapshot.hasMore) {
snapshot.fetchMore();
}
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
itemBuilder(context, doc),
if (isLastItem && snapshot.hasMore)
fetchingIndicatorBuilder?.call(context) ??
const Padding(
padding: EdgeInsets.symmetric(
vertical: 16.0,
),
child: Center(
child: LoadingIndicator(
size: 30.0,
borderWidth: 2.0,
),
),
),
],
),
)
: itemBuilder(context, doc);
},
scrollDirection: scrollDirection,
reverse: reverse,
controller: controller,
primary: primary,
physics: physics,
shrinkWrap: shrinkWrap,
padding: padding,
itemExtent: itemExtent,
prototypeItem: prototypeItem,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
// ignore: deprecated_member_use
cacheExtent: cacheExtent,
semanticChildCount: semanticChildCount,
dragStartBehavior: dragStartBehavior,
keyboardDismissBehavior: keyboardDismissBehavior,
restorationId: restorationId,
clipBehavior: clipBehavior,
);
},
);
/// Shows a separator between list items just as in [ListView.separated]
FirestoreListView.separated({
super.key,
required super.query,
required FirestoreItemBuilder<Document> itemBuilder,
super.pageSize,
super.includeMetadataChanges,
FirestoreLoadingBuilder? loadingBuilder,
FirestoreFetchingIndicatorBuilder? fetchingIndicatorBuilder,
FirestoreErrorBuilder? errorBuilder,
FirestoreEmptyBuilder? emptyBuilder,
required IndexedWidgetBuilder separatorBuilder,
Axis scrollDirection = Axis.vertical,
bool showFetchingIndicator = false,
bool reverse = false,
ScrollController? controller,
bool? primary,
ScrollPhysics? physics,
bool shrinkWrap = false,
EdgeInsetsGeometry? padding,
ChildIndexGetter? findChildIndexCallback,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
double? cacheExtent,
DragStartBehavior dragStartBehavior = DragStartBehavior.start,
ScrollViewKeyboardDismissBehavior keyboardDismissBehavior =
ScrollViewKeyboardDismissBehavior.manual,
String? restorationId,
Clip clipBehavior = Clip.hardEdge,
}) : super(
builder: (context, snapshot, _) {
if (snapshot.isFetching) {
return loadingBuilder?.call(context) ??
const Center(child: CircularProgressIndicator.adaptive());
}
if (snapshot.hasError && errorBuilder != null) {
return errorBuilder(
context,
snapshot.error!,
snapshot.stackTrace!,
);
}
if (snapshot.docs.isEmpty && emptyBuilder != null) {
return emptyBuilder(context);
}
final itemCount = snapshot.docs.length;
return ListView.separated(
itemCount: itemCount,
itemBuilder: (context, index) {
final isLastItem = index + 1 == itemCount;
if (!showFetchingIndicator && isLastItem && snapshot.hasMore) {
snapshot.fetchMore();
}
final doc = snapshot.docs[index];
return showFetchingIndicator
? OnMountListener(
onMount: () {
if (isLastItem && snapshot.hasMore) {
snapshot.fetchMore();
}
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
itemBuilder(context, doc),
if (isLastItem && snapshot.hasMore)
fetchingIndicatorBuilder?.call(context) ??
const Padding(
padding: EdgeInsets.symmetric(
vertical: 16.0,
),
child: Center(
child: LoadingIndicator(
size: 30.0,
borderWidth: 2.0,
),
),
),
],
),
)
: itemBuilder(context, doc);
},
separatorBuilder: separatorBuilder,
scrollDirection: scrollDirection,
reverse: reverse,
controller: controller,
primary: primary,
physics: physics,
shrinkWrap: shrinkWrap,
padding: padding,
// ignore: deprecated_member_use
findChildIndexCallback: findChildIndexCallback,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
// ignore: deprecated_member_use
cacheExtent: cacheExtent,
dragStartBehavior: dragStartBehavior,
keyboardDismissBehavior: keyboardDismissBehavior,
restorationId: restorationId,
clipBehavior: clipBehavior,
);
},
);
}
/// Listens to an aggregate query and passes the [AsyncSnapshot] to the builder.
class AggregateQueryBuilder extends StatefulWidget {
/// A query to listen to
final AggregateQuery query;
/// A builder that is called whenever the query is updated.
final Widget Function(
BuildContext context,
AsyncSnapshot<AggregateQuerySnapshot> snapshot,
) builder;
const AggregateQueryBuilder({
super.key,
required this.query,
required this.builder,
});
@override
State<AggregateQueryBuilder> createState() => _AggregateQueryBuilderState();
}
class _AggregateQueryBuilderState extends State<AggregateQueryBuilder> {
late var queryFuture = widget.query.get();
@override
Widget build(BuildContext context) {
return FutureBuilder<AggregateQuerySnapshot>(
future: queryFuture,
builder: (context, snapshot) {
return widget.builder(context, snapshot);
},
);
}
@override
void didUpdateWidget(covariant AggregateQueryBuilder oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.query != oldWidget.query) {
queryFuture = widget.query.get();
}
}
}
/// This widget calls back, via the supplied onMount method, when it gets
/// mounted.
/// It also offers the functionality to safely delay the onMount callback by
/// onMountDelay.
///
/// Borrowed the idea from the link below and built on it further:
/// https://www.filledstacks.com/post/how-to-perform-real-time-pagination-with-firestore/?utm_source=pocket_reader
class OnMountListener extends StatefulWidget {
final Function onMount;
final int onMountDelay; // in milliseconds
final Widget child;
const OnMountListener({
super.key,
required this.onMount,
this.onMountDelay = 500,
required this.child,
});
@override
State<OnMountListener> createState() => _OnMountListenerState();
}
class _OnMountListenerState extends State<OnMountListener> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
Future.delayed(Duration(milliseconds: widget.onMountDelay), () {
if (mounted) widget.onMount();
});
});
}
@override
Widget build(BuildContext context) {
return widget.child;
}
}