-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathfirestore.dart
1260 lines (1099 loc) · 40 KB
/
firestore.dart
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ignore_for_file: non_constant_identifier_names, avoid_print
import 'dart:math';
import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_snippets_app/model/firestore_add_data_custom_objects_snippet.dart';
import 'package:firebase_snippets_app/model/restaurant.dart';
import 'package:firebase_snippets_app/snippets/snippet_base.dart';
import 'package:http/http.dart' as http;
class FirestoreSnippets extends DocSnippet {
@override
final FirebaseFirestore db;
FirestoreSnippets(this.db);
@override
void runAll() {
getStarted_addData();
getStarted_addData2();
getStarted_readData();
dataModel_references();
dataModel_subCollections();
getDataOnce_getAllDocumentsInASubcollection();
}
void getStarted_addData() async {
// [START get_started_add_data_1]
// Create a new user with a first and last name
final user = <String, dynamic>{
"first": "Ada",
"last": "Lovelace",
"born": 1815
};
// Add a new document with a generated ID
db.collection("users").add(user).then((DocumentReference doc) =>
print('DocumentSnapshot added with ID: ${doc.id}'));
// [END get_started_add_data_1]
}
void getStarted_addData2() async {
// [START get_started_add_data_2]
// Create a new user with a first and last name
final user = <String, dynamic>{
"first": "Alan",
"middle": "Mathison",
"last": "Turing",
"born": 1912
};
// Add a new document with a generated ID
db.collection("users").add(user).then((DocumentReference doc) =>
print('DocumentSnapshot added with ID: ${doc.id}'));
// [END get_started_add_data_2]
}
void getStarted_readData() async {
// [START get_started_read_data]
await db.collection("users").get().then((event) {
for (var doc in event.docs) {
print("${doc.id} => ${doc.data()}");
}
});
// [END get_started_read_data]
}
void dataModel_references() {
// [START data_model_references]
final alovelaceDocumentRef = db.collection("users").doc("alovelace");
// [END data_model_references]
// [START data_model_references2]
final usersCollectionRef = db.collection("users");
// [END data_model_references2]
// [START data_model_references3]
final aLovelaceDocRef = db.doc("users/alovelace");
// [END data_model_references3]
}
void dataModel_subCollections() {
// [START data_model_sub_collections]
final messageRef = db
.collection("rooms")
.doc("roomA")
.collection("messages")
.doc("message1");
// [END data_model_sub_collections]
}
void dataBundles_loadingClientBundles() async {
// [START data_bundles_loading_client_bundles]
// Get a bundle from a server
final url = Uri.https('example.com', '/create-bundle');
final response = await http.get(url);
String body = response.body;
final buffer = Uint8List.fromList(body.codeUnits);
// Load a bundle from a buffer
LoadBundleTask task = FirebaseFirestore.instance.loadBundle(buffer);
await task.stream.toList();
// Use the cached named query
final results = await FirebaseFirestore.instance.namedQueryGet(
"latest-stories-query",
options: const GetOptions(
source: Source.cache,
),
);
// [END data_bundles_loading_client_bundles]
}
void addData_setADocument() {
// [START add_data_set_document_1]
final city = <String, String>{
"name": "Los Angeles",
"state": "CA",
"country": "USA"
};
db
.collection("cities")
.doc("LA")
.set(city)
.onError((e, _) => print("Error writing document: $e"));
// [END add_data_set_document_1]
}
void addData_setADocument2() {
// [START add_data_set_document_2]
// Update one field, creating the document if it does not already exist.
final data = {"capital": true};
db.collection("cities").doc("BJ").set(data, SetOptions(merge: true));
// [END add_data_set_document_2]
}
void addData_dataTypes() {
// [START add_data_data_types]
final docData = {
"stringExample": "Hello world!",
"booleanExample": true,
"numberExample": 3.14159265,
"dateExample": Timestamp.now(),
"listExample": [1, 2, 3],
"nullExample": null
};
final nestedData = {
"a": 5,
"b": true,
};
docData["objectExample"] = nestedData;
db
.collection("data")
.doc("one")
.set(docData)
.onError((e, _) => print("Error writing document: $e"));
// [END add_data_data_types]
}
void addData_customObjects2() async {
// [START add_data_custom_objects2]
final city = City(
name: "Los Angeles",
state: "CA",
country: "USA",
capital: false,
population: 5000000,
regions: ["west_coast", "socal"],
);
final docRef = db
.collection("cities")
.withConverter(
fromFirestore: City.fromFirestore,
toFirestore: (City city, options) => city.toFirestore(),
)
.doc("LA");
await docRef.set(city);
// [END add_data_custom_objects2]
}
void addData_addADocument() {
// [START add_data_add_a_document]
db.collection("cities").doc("new-city-id").set({"name": "Chicago"});
// [END add_data_add_a_document]
}
void addData_addADocument2() {
// [START add_data_add_a_document_2]
// Add a new document with a generated id.
final data = {"name": "Tokyo", "country": "Japan"};
db.collection("cities").add(data).then((documentSnapshot) =>
print("Added Data with ID: ${documentSnapshot.id}"));
// [END add_data_add_a_document_2]
}
void addData_addADocument3() {
// [START add_data_add_a_document_3]
// Add a new document with a generated id.
final data = <String, dynamic>{};
final newCityRef = db.collection("cities").doc();
// Later...
newCityRef.set(data);
// [END add_data_add_a_document_3]
}
void addData_updateADocument() {
// [START add_data_update_a_document]
final washingtonRef = db.collection("cites").doc("DC");
washingtonRef.update({"capital": true}).then(
(value) => print("DocumentSnapshot successfully updated!"),
onError: (e) => print("Error updating document $e"));
// [END add_data_update_a_document]
}
void addData_serverTimestamp() {
// [START add_data_server_timestamp]
final docRef = db.collection("objects").doc("some-id");
final updates = <String, dynamic>{
"timestamp": FieldValue.serverTimestamp(),
};
docRef.update(updates).then(
(value) => print("DocumentSnapshot successfully updated!"),
onError: (e) => print("Error updating document $e"));
// [END add_data_server_timestamp]
}
void addData_updateFieldsInNestedObjects() {
// [START add_data_update_fields_in_nested_objects]
// Assume the document contains:
// {
// name: "Frank",
// favorites: { food: "Pizza", color: "Blue", subject: "recess" }
// age: 12
// }
db
.collection("users")
.doc("frank")
.update({"age": 13, "favorites.color": "Red"});
// [END add_data_update_fields_in_nested_objects]
}
void addData_updateElementsInArray() {
// [START add_data_update_elements_in_array]
final washingtonRef = db.collection("cities").doc("DC");
// Atomically add a new region to the "regions" array field.
washingtonRef.update({
"regions": FieldValue.arrayUnion(["greater_virginia"]),
});
// Atomically remove a region from the "regions" array field.
washingtonRef.update({
"regions": FieldValue.arrayRemove(["east_coast"]),
});
// [END add_data_update_elements_in_array]
}
void addData_incrementANumericValue() {
// [START add_data_increment_a_numeric_value]
var washingtonRef = db.collection('cities').doc('DC');
// Atomically increment the population of the city by 50.
washingtonRef.update(
{"population": FieldValue.increment(50)},
);
// [END add_data_increment_a_numeric_value]
}
void transactions_updatingDataWithTransactions() {
// [START transactions_updating_data_with_transactions]
final sfDocRef = db.collection("cities").doc("SF");
db.runTransaction((transaction) async {
final snapshot = await transaction.get(sfDocRef);
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
final newPopulation = snapshot.get("population") + 1;
transaction.update(sfDocRef, {"population": newPopulation});
}).then(
(value) => print("DocumentSnapshot successfully updated!"),
onError: (e) => print("Error updating document $e"),
);
// [END transactions_updating_data_with_transactions]
}
void transactions_passingInformationOutOfTransactions() {
// TODO: ewindmill@ - either the above example (using asnyc) or this example
// using (then) is "more correct". Figure out which one.
// [START transactions_passing_information_out_of_transactions]
final sfDocRef = db.collection("cities").doc("SF");
db.runTransaction((transaction) {
return transaction.get(sfDocRef).then((sfDoc) {
final newPopulation = sfDoc.get("population") + 1;
transaction.update(sfDocRef, {"population": newPopulation});
return newPopulation;
});
}).then(
(newPopulation) => print("Population increased to $newPopulation"),
onError: (e) => print("Error updating document $e"),
);
// [END transactions_passing_information_out_of_transactions]
}
void transactions_batchedWrites() {
// [START transactions_batched_writes]
// Get a new write batch
final batch = db.batch();
// Set the value of 'NYC'
var nycRef = db.collection("cities").doc("NYC");
batch.set(nycRef, {"name": "New York City"});
// Update the population of 'SF'
var sfRef = db.collection("cities").doc("SF");
batch.update(sfRef, {"population": 1000000});
// Delete the city 'LA'
var laRef = db.collection("cities").doc("LA");
batch.delete(laRef);
// Commit the batch
batch.commit().then((_) {
// ...
});
// [END transactions_batched_writes]
}
void deleteData_deleteDocs() {
// [START delete_data_delete_docs]
db.collection("cities").doc("DC").delete().then(
(doc) => print("Document deleted"),
onError: (e) => print("Error updating document $e"),
);
// [END delete_data_delete_docs]
}
void deleteData_deleteFields() {
// [START delete_data_delete_fields]
final docRef = db.collection("cities").doc("BJ");
// Remove the 'capital' field from the document
final updates = <String, dynamic>{
"capital": FieldValue.delete(),
};
docRef.update(updates);
// [END delete_data_delete_fields]
}
void getDataOnce_exampleData() {
// [START get_data_once_example_data]
final cities = db.collection("cities");
final data1 = <String, dynamic>{
"name": "San Francisco",
"state": "CA",
"country": "USA",
"capital": false,
"population": 860000,
"regions": ["west_coast", "norcal"]
};
cities.doc("SF").set(data1);
final data2 = <String, dynamic>{
"name": "Los Angeles",
"state": "CA",
"country": "USA",
"capital": false,
"population": 3900000,
"regions": ["west_coast", "socal"],
};
cities.doc("LA").set(data2);
final data3 = <String, dynamic>{
"name": "Washington D.C.",
"state": null,
"country": "USA",
"capital": true,
"population": 680000,
"regions": ["east_coast"]
};
cities.doc("DC").set(data3);
final data4 = <String, dynamic>{
"name": "Tokyo",
"state": null,
"country": "Japan",
"capital": true,
"population": 9000000,
"regions": ["kanto", "honshu"]
};
cities.doc("TOK").set(data4);
final data5 = <String, dynamic>{
"name": "Beijing",
"state": null,
"country": "China",
"capital": true,
"population": 21500000,
"regions": ["jingjinji", "hebei"],
};
cities.doc("BJ").set(data5);
// [END get_data_once_example_data]
}
void getDataOnce_getADocument() {
// [START get_data_once_get_a_document]
final docRef = db.collection("cities").doc("SF");
docRef.get().then(
(DocumentSnapshot doc) {
final data = doc.data() as Map<String, dynamic>;
// ...
},
onError: (e) => print("Error getting document: $e"),
);
// [END get_data_once_get_a_document]
}
void getDataOnce_sourceOptions() {
// [START get_data_once_source_options]
final docRef = db.collection("cities").doc("SF");
// Source can be CACHE, SERVER, or DEFAULT.
const source = Source.cache;
docRef.get(const GetOptions(source: source)).then(
(res) => print("Successfully completed"),
onError: (e) => print("Error completing: $e"),
);
// [END get_data_once_source_options]
}
void getDataOnce_customObjects() async {
// [START get_data_once_custom_objects]
final ref = db.collection("cities").doc("LA").withConverter(
fromFirestore: City.fromFirestore,
toFirestore: (City city, _) => city.toFirestore(),
);
final docSnap = await ref.get();
final city = docSnap.data(); // Convert to City object
if (city != null) {
print(city);
} else {
print("No such document.");
}
// [END get_data_once_custom_objects]
}
void getDataOnce_multipleDocumentsFromACollection() {
// [START get_data_once_multiple_documents_from_a_collection]
db.collection("cities").where("capital", isEqualTo: true).get().then(
(querySnapshot) {
print("Successfully completed");
for (var docSnapshot in querySnapshot.docs) {
print('${docSnapshot.id} => ${docSnapshot.data()}');
}
},
onError: (e) => print("Error completing: $e"),
);
// [END get_data_once_multiple_documents_from_a_collection]
}
void getDataOnce_getAllDocumentsInACollection() {
// [START get_data_once_get_all_documents_in_a_collection]
db.collection("cities").get().then(
(querySnapshot) {
print("Successfully completed");
for (var docSnapshot in querySnapshot.docs) {
print('${docSnapshot.id} => ${docSnapshot.data()}');
}
},
onError: (e) => print("Error completing: $e"),
);
// [END get_data_once_get_all_documents_in_a_collection]
}
void getDataOnce_getAllDocumentsInASubcollection() {
// [START get_data_once_get_all_documents_in_a_subcollection]
// [START firestore_query_subcollection]
db.collection("cities").doc("SF").collection("landmarks").get().then(
(querySnapshot) {
print("Successfully completed");
for (var docSnapshot in querySnapshot.docs) {
print('${docSnapshot.id} => ${docSnapshot.data()}');
}
},
onError: (e) => print("Error completing: $e"),
);
// [END firestore_query_subcollection]
// [END get_data_once_get_all_documents_in_a_subcollection]
}
void getDataOnce_listSubCollections() {
// [START get_data_once_list_sub_collections]
// Not currently available in Dart SDK
// [END get_data_once_list_sub_collections]
}
void listenToRealtimeUpdates_listenForUpdates() {
// [START listen_to_realtime_updates_listen_for_updates]
final docRef = db.collection("cities").doc("SF");
docRef.snapshots().listen(
(event) => print("current data: ${event.data()}"),
onError: (error) => print("Listen failed: $error"),
);
// [END listen_to_realtime_updates_listen_for_updates]
}
void listenToRealtimeUpdates_eventsForLocalChanges() {
// [START listen_to_realtime_updates_events_for_local_changes]
final docRef = db.collection("cities").doc("SF");
docRef.snapshots().listen(
(event) {
final source = (event.metadata.hasPendingWrites) ? "Local" : "Server";
print("$source data: ${event.data()}");
},
onError: (error) => print("Listen failed: $error"),
);
// [END listen_to_realtime_updates_events_for_local_changes]
}
void listenToRealtimeUpdates_eventsOnMetadataChanges() {
// [START listen_to_realtime_updates_events_on_metadata_changes]
final docRef = db.collection("cities").doc("SF");
docRef.snapshots(includeMetadataChanges: true).listen((event) {
// ...
});
// [END listen_to_realtime_updates_events_on_metadata_changes]
}
void listenToRealtimeUpdates_listToMultipleDocuments() {
// [START listen_to_realtime_updates_list_to_multiple_documents]
db
.collection("cities")
.where("state", isEqualTo: "CA")
.snapshots()
.listen((event) {
final cities = [];
for (var doc in event.docs) {
cities.add(doc.data()["name"]);
}
print("cities in CA: ${cities.join(", ")}");
});
// [END listen_to_realtime_updates_list_to_multiple_documents]
}
void listenToRealtimeUpdates_viewUpdatesBetweenChanges() {
// [START listen_to_realtime_updates_view_updates_between_changes]
db
.collection("cities")
.where("state", isEqualTo: "CA")
.snapshots()
.listen((event) {
for (var change in event.docChanges) {
switch (change.type) {
case DocumentChangeType.added:
print("New City: ${change.doc.data()}");
break;
case DocumentChangeType.modified:
print("Modified City: ${change.doc.data()}");
break;
case DocumentChangeType.removed:
print("Removed City: ${change.doc.data()}");
break;
}
}
});
// [END listen_to_realtime_updates_view_updates_between_changes]
}
void listenToRealtimeUpdates_detachAListener() {
// [START listen_to_realtime_updates_detach_a_listener]
final collection = db.collection("cities");
final listener = collection.snapshots().listen((event) {
// ...
});
listener.cancel();
// [END listen_to_realtime_updates_detach_a_listener]
}
void listenToRealtimeUpdates_handleListenErrors() {
// [START listen_to_realtime_updates_handle_listen_errors]
final docRef = db.collection("cities");
docRef.snapshots().listen(
(event) => print("listener attached"),
onError: (error) => print("Listen failed: $error"),
);
// [END listen_to_realtime_updates_handle_listen_errors]
}
void performSimpleAndCompoundQueries_exampleData() {
// [START perform_simple_and_compound_queries_example_data]
final cities = db.collection("cities");
final data1 = <String, dynamic>{
"name": "San Francisco",
"state": "CA",
"country": "USA",
"capital": false,
"population": 860000,
"regions": ["west_coast", "norcal"]
};
cities.doc("SF").set(data1);
final data2 = <String, dynamic>{
"name": "Los Angeles",
"state": "CA",
"country": "USA",
"capital": false,
"population": 3900000,
"regions": ["west_coast", "socal"],
};
cities.doc("LA").set(data2);
final data3 = <String, dynamic>{
"name": "Washington D.C.",
"state": null,
"country": "USA",
"capital": true,
"population": 680000,
"regions": ["east_coast"]
};
cities.doc("DC").set(data3);
final data4 = <String, dynamic>{
"name": "Tokyo",
"state": null,
"country": "Japan",
"capital": true,
"population": 9000000,
"regions": ["kanto", "honshu"]
};
cities.doc("TOK").set(data4);
final data5 = <String, dynamic>{
"name": "Beijing",
"state": null,
"country": "China",
"capital": true,
"population": 21500000,
"regions": ["jingjinji", "hebei"],
};
cities.doc("BJ").set(data5);
// [END perform_simple_and_compound_queries_example_data]
}
void performSimpleAndCompoundQueries_simpleQueries() {
// [START perform_simple_and_compound_queries_simple_queries]
// Create a reference to the cities collection
final citiesRef = db.collection("cities");
// Create a query against the collection.
final query = citiesRef.where("state", isEqualTo: "CA");
// [END perform_simple_and_compound_queries_simple_queries]
}
void performSimpleAndCompoundQueries_simpleQueries2() {
// [START perform_simple_and_compound_queries_simple_queries2]
final capitalcities =
db.collection("cities").where("capital", isEqualTo: true);
// [END perform_simple_and_compound_queries_simple_queries2]
}
void performSimpleAndCompoundQueries_executeAQuery() {
// [START perform_simple_and_compound_queries_execute_a_query]
db.collection("cities").where("capital", isEqualTo: true).get().then(
(res) => print("Successfully completed"),
onError: (e) => print("Error completing: $e"),
);
// [END perform_simple_and_compound_queries_execute_a_query]
}
void performSimpleAndCompoundQueries_queryOperators() {
// [START perform_simple_and_compound_queries_query_operators]
final citiesRef = db.collection("cities");
final stateQuery = citiesRef.where("state", isEqualTo: "CA");
final populationQuery = citiesRef.where("population", isLessThan: 100000);
final nameQuery = citiesRef.where("name", isEqualTo: "San Francisco");
// [END perform_simple_and_compound_queries_query_operators]
}
void performSimpleAndCompoundQueries_notEqual() {
// [START perform_simple_and_compound_queries_not_equal]
final citiesRef = db.collection("cities");
final notCapitals = citiesRef.where("capital", isNotEqualTo: true);
// [END perform_simple_and_compound_queries_not_equal]
}
void performSimpleAndCompoundQueries_arrayMembership() {
// [START perform_simple_and_compound_queries_array_membership]
final citiesRef = db.collection("cities");
final westCoastcities =
citiesRef.where("regions", arrayContains: "west_coast");
// [END perform_simple_and_compound_queries_array_membership]
}
void performSimpleAndCompoundQueries_inNotInArrayContainsAny() {
// [START perform_simple_and_compound_queries_in_not_in_array_contains_any]
final citiesRef = db.collection("cities");
final cities = citiesRef.where("country", whereIn: ["USA", "Japan"]);
// [END perform_simple_and_compound_queries_in_not_in_array_contains_any]
}
void performSimpleAndCompoundQueries_notIn() {
// [START perform_simple_and_compound_queries_not_in]
final citiesRef = db.collection("cities");
final cities = citiesRef.where("country", whereNotIn: ["USA", "Japan"]);
// [END perform_simple_and_compound_queries_not_in]
}
void performSimpleAndCompoundQueries_arrayContainsAny() {
// [START perform_simple_and_compound_queries_array_contains_any]
final citiesRef = db.collection("cities");
final cities = citiesRef
.where("regions", arrayContainsAny: ["west_coast", "east_coast"]);
// [END perform_simple_and_compound_queries_array_contains_any]
}
void performSimpleAndCompoundQueries_inArray() {
// [START perform_simple_and_compound_queries_array_wherein]
final citiesRef = db.collection("cities");
final cities = citiesRef.where("regions", whereIn: [
["west_coast"],
["east_coast"]
]);
// [END perform_simple_and_compound_queries_array_wherein]
}
void performSimpleAndCompoundQueries_compoundQueries() {
// [START perform_simple_and_compound_queries_compound_queries]
final citiesRef = db.collection("cities");
citiesRef
.where("state", isEqualTo: "CO")
.where("name", isEqualTo: "Denver");
citiesRef
.where("state", isEqualTo: "CA")
.where("population", isLessThan: 1000000);
// [END perform_simple_and_compound_queries_compound_queries]
}
// TODO: remember to document this naming convention in README
void performSimpleAndCompoundQueries_compoundQueries_validRangeFilters() {
// [START perform_simple_and_compound_queries_compound_queries_valid_range_filters]
final citiesRef = db.collection("cities");
citiesRef
.where("state", isGreaterThanOrEqualTo: "CA")
.where("state", isLessThanOrEqualTo: "IN");
citiesRef
.where("state", isEqualTo: "CA")
.where("population", isGreaterThan: 1000000);
// [END perform_simple_and_compound_queries_compound_queries_valid_range_filters]
}
void performSimpleAndCompoundQueries_compoundQueries_invalidRangeFilters() {
// [START perform_simple_and_compound_queries_compound_queries_invalid_range_filters]
final citiesRef = db.collection("cities");
citiesRef
.where("state", isGreaterThanOrEqualTo: "CA")
.where("population", isGreaterThan: 1000000);
// [END perform_simple_and_compound_queries_compound_queries_invalid_range_filters]
}
void performSimpleAndCompoundQueries_collectionGroups() {
// [START perform_simple_and_compound_queries_collection_groups]
final citiesRef = db.collection("cities");
final ggbData = {"name": "Golden Gate Bridge", "type": "bridge"};
citiesRef.doc("SF").collection("landmarks").add(ggbData);
final lohData = {"name": "Legion of Honor", "type": "museum"};
citiesRef.doc("SF").collection("landmarks").add(lohData);
final gpData = {"name": "Griffth Park", "type": "park"};
citiesRef.doc("LA").collection("landmarks").add(gpData);
final tgData = {"name": "The Getty", "type": "museum"};
citiesRef.doc("LA").collection("landmarks").add(tgData);
final lmData = {"name": "Lincoln Memorial", "type": "memorial"};
citiesRef.doc("DC").collection("landmarks").add(lmData);
final nasaData = {
"name": "National Air and Space Museum",
"type": "museum"
};
citiesRef.doc("DC").collection("landmarks").add(nasaData);
final upData = {"name": "Ueno Park", "type": "park"};
citiesRef.doc("TOK").collection("landmarks").add(upData);
final nmData = {
"name": "National Musuem of Nature and Science",
"type": "museum"
};
citiesRef.doc("TOK").collection("landmarks").add(nmData);
final jpData = {"name": "Jingshan Park", "type": "park"};
citiesRef.doc("BJ").collection("landmarks").add(jpData);
final baoData = {"name": "Beijing Ancient Observatory", "type": "musuem"};
citiesRef.doc("BJ").collection("landmarks").add(baoData);
// [END perform_simple_and_compound_queries_collection_groups]
}
void performSimpleAndCompoundQueries_collectionGroups2() {
// [START perform_simple_and_compound_queries_collection_groups2]
db
.collectionGroup("landmarks")
.where("type", isEqualTo: "museum")
.get()
.then(
(res) => print("Successfully completed"),
onError: (e) => print("Error completing: $e"),
);
// [END perform_simple_and_compound_queries_collection_groups2]
}
void filterQuery_or() {
// [START firestore_query_filter_or]
var query = db.collection("cities").where(
Filter.or(
Filter("capital", isEqualTo: true),
Filter("population", isGreaterThan: 1000000),
),
);
// [END firestore_query_filter_or]
}
void filterQuery_or2() {
// [START firestore_query_filter_or_compound]
var query = db.collection("cities").where(
Filter.and(
Filter("state", isEqualTo: "CA"),
Filter.or(
Filter("capital", isEqualTo: true),
Filter("population", isGreaterThan: 1000000),
),
),
);
// [END firestore_query_filter_or_compound]
}
void aggregationQuery_count() {
// [START count_aggregate_collection]
// Returns number of documents in users collection
db.collection("cities").count().get().then(
(res) => print(res.count),
onError: (e) => print("Error completing: $e"),
);
// [END count_aggregate_collection]
}
void aggregationQuery_count2() {
// [START count_aggregate_query]
// This also works with collection queries.
db.collection("cities").where("capital", isEqualTo: 10).count().get().then(
(res) => print(res.count),
onError: (e) => print("Error completing: $e"),
);
// [END count_aggregate_query]
}
void aggregationQuery_sum() {
// [START sum_aggregate_collection]
db.collection("cities").aggregate(sum("population")).get().then(
(res) => print(res.getAverage("population")),
onError: (e) => print("Error completing: $e"),
);
// [END sum_aggregate_collection]
}
void aggregationQuery_sum2() {
// [START sum_aggregate_query]
db
.collection("cities")
.where("capital", isEqualTo: true)
.aggregate(sum("population"))
.get()
.then(
(res) => print(res.getAverage("population")),
onError: (e) => print("Error completing: $e"),
);
// [END sum_aggregate_query]
}
void aggregationQuery_average() {
// [START average_aggregate_collection]
db.collection("cities").aggregate(average("population")).get().then(
(res) => print(res.getAverage("population")),
onError: (e) => print("Error completing: $e"),
);
// [END average_aggregate_collection]
}
void aggregationQuery_average2() {
// [START average_aggregate_query]
db
.collection("cities")
.where("capital", isEqualTo: true)
.aggregate(average("population"))
.get()
.then(
(res) => print(res.getAverage("population")),
onError: (e) => print("Error completing: $e"),
);
// [END average_aggregate_query]
}
void multipleAggregateQueries() {
// [START multi_aggregate_query]
db
.collection("cities")
.aggregate(
count(),
sum("population"),
average("population"),
)
.get()
.then(
(res) {
print(res.count);
print(res.getSum("population"));
print(res.getAverage("population"));
},
onError: (e) => print("Error completing: $e"),
);
// [END multi_aggregate_query]
}
void orderAndLimitData_orderAndLimitData() {
// [START order_and_limit_data_order_and_limit_data]
final citiesRef = db.collection("cities");
citiesRef.orderBy("name").limit(3);
// [END order_and_limit_data_order_and_limit_data]
}
void orderAndLimitData_orderAndLimitData2() {
// [START order_and_limit_data_order_and_limit_data2]
final citiesRef = db.collection("cities");
citiesRef.orderBy("name", descending: true).limit(3);
// [END order_and_limit_data_order_and_limit_data2]
}
void orderAndLimitData_orderAndLimitData3() {
// [START order_and_limit_data_order_and_limit_data3]
final citiesRef = db.collection("cities");
citiesRef.orderBy("state").orderBy("population", descending: true);
// [END order_and_limit_data_order_and_limit_data3]
}
void orderAndLimitData_orderAndLimitData4() {
// [START order_and_limit_data_order_and_limit_data4]
final citiesRef = db.collection("cities");
citiesRef
.where("population", isGreaterThan: 100000)
.orderBy("population")
.limit(2);
// [END order_and_limit_data_order_and_limit_data4]
}
void orderAndLimitData_limitations_valid() {
// [START order_and_limit_data_limitations_valid]
final citiesRef = db.collection("cities");
citiesRef.where("population", isGreaterThan: 100000).orderBy("population");
// [END order_and_limit_data_limitations_valid]
}
void orderAndLimitData_limitations_invalid() {
// [START order_and_limit_data_limitations_invalid]
final citiesRef = db.collection("cities");
citiesRef.where("population", isGreaterThan: 100000).orderBy("country");
// [END order_and_limit_data_limitations_invalid]
}
void paginateData_addASimpleCursor() {