FavouriteFruitsView.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import FirebaseFirestore
  15. import SwiftUI
  16. private struct Fruit: Codable, Identifiable, Equatable {
  17. @DocumentID var id: String?
  18. var name: String
  19. var isFavourite: Bool
  20. }
  21. /// This view demonstrates how to use the `FirestoreQuery` property wrapper.
  22. struct FavouriteFruitsView: View {
  23. @FirestoreQuery(
  24. collectionPath: "fruits",
  25. predicates: [
  26. .where("isFavourite", isEqualTo: true),
  27. ]
  28. ) fileprivate var fruitResults: Result<[Fruit], Error>
  29. @State var showOnlyFavourites = true
  30. var body: some View {
  31. if case let .success(fruits) = fruitResults {
  32. List(fruits) { fruit in
  33. Text(fruit.name)
  34. }
  35. .animation(.default, value: fruits)
  36. .navigationTitle("Fruits")
  37. .toolbar {
  38. ToolbarItem(placement: .navigationBarTrailing) {
  39. Button(action: toggleFilter) {
  40. Image(systemName: showOnlyFavourites
  41. ? "line.3.horizontal.decrease.circle.fill"
  42. : "line.3.horizontal.decrease.circle")
  43. }
  44. }
  45. }
  46. } else if case let .failure(error) = fruitResults {
  47. // Handle error
  48. Text("Couldn't map data: \(error.localizedDescription)")
  49. }
  50. }
  51. func toggleFilter() {
  52. showOnlyFavourites.toggle()
  53. if showOnlyFavourites {
  54. $fruitResults.predicates = [
  55. .whereField("isFavourite", isEqualTo: true),
  56. ]
  57. } else {
  58. $fruitResults.predicates = []
  59. }
  60. }
  61. }
  62. struct FavouriteFruitsView_Previews: PreviewProvider {
  63. static var previews: some View {
  64. FavouriteFruitsView()
  65. }
  66. }