FavouriteFruitsView.swift 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 SwiftUI
  15. import FirebaseFirestoreSwift
  16. private struct Fruit: Codable, Identifiable, Equatable {
  17. @DocumentID var id: String?
  18. var name: String
  19. var isFavourite: Bool
  20. }
  21. struct FavouriteFruitsView: View {
  22. @FirestoreQuery(
  23. collectionPath: "fruits",
  24. predicates: [
  25. .where("isFavourite", isEqualTo: true),
  26. ]
  27. ) fileprivate var fruitResults: Result<[Fruit], Error>
  28. @State var showOnlyFavourites = true
  29. var body: some View {
  30. if case let .success(fruits) = fruitResults {
  31. List(fruits) { fruit in
  32. Text(fruit.name)
  33. }
  34. .animation(.default, value: fruits)
  35. .navigationTitle("Fruits")
  36. .toolbar {
  37. ToolbarItem(placement: .navigationBarTrailing) {
  38. Button(action: toggleFilter) {
  39. Image(systemName: showOnlyFavourites
  40. ? "line.3.horizontal.decrease.circle.fill"
  41. : "line.3.horizontal.decrease.circle")
  42. }
  43. }
  44. }
  45. } else if case let .failure(error) = fruitResults {
  46. // Handle error
  47. Text("Couldn't map data: \(error.localizedDescription)")
  48. }
  49. }
  50. func toggleFilter() {
  51. showOnlyFavourites.toggle()
  52. if showOnlyFavourites {
  53. $fruitResults.predicates = [
  54. .whereField("isFavourite", isEqualTo: true),
  55. ]
  56. } else {
  57. $fruitResults.predicates = []
  58. }
  59. }
  60. }
  61. struct FavouriteFruitsView_Previews: PreviewProvider {
  62. static var previews: some View {
  63. FavouriteFruitsView()
  64. }
  65. }