SwiftUI搜索栏无法生成诊断错误



我正在尝试使用本教程实现一个搜索栏:https://www.appcoda.com/swiftui-search-bar。

我可以让搜索栏显示并获取文本,但它对文本没有任何作用,因为现阶段没有使用它进行过滤。

当我尝试使用它来过滤我的产品列表(取自Firestore(时,它会抛出一个Failed to produce diagnostic for expression; please submit a bug report错误。

struct ProductList: View {
@State private var searchText: String = ""

// ProductsModel() is the Class that this structure is looking at. If anything in ProductsModel changes, then - because it is an ObservableObject - then this structure/view ProductList will update with the new information.
@ObservedObject private var viewModel = ProductsModel()

var body: some View {
NavigationView{
VStack{

HStack{
NavigationLink(destination: ProductCreationView()){Text("Add Product")}
NavigationLink(destination: Initialinfo()){Text("Help")}
} //Navigation Links

SearchBar(text: $searchText)

List(viewModel.product_fire.filter({ searchText.isEmpty ? true : $0.product_name.contains(searchText) })){ product in
NavigationLink(destination: ProductDetail(product: product))
{ItemRow(product: product).navigationBarTitle("Products", displayMode: .inline)}
}.onAppear(){
self.viewModel.fetchData()
}


// Create a list of all products where each product is given a link that points to the specific product detail page as well as the description taken from the ItemRow view for that product.
// This displays as : Product Name/Link
//                      Product Brand
//                    ...
List(viewModel.product_fire, id:.product_name) { product in
NavigationLink(destination: ProductDetail(product: product))
{ItemRow(product: product).navigationBarTitle("Products", displayMode: .inline)}
}.onAppear(){
self.viewModel.fetchData()
}

如果我注释掉过滤版本的代码,它会显示良好,并从数据库中提取所有产品,并将每个产品的名称/链接和品牌作为一对显示为一个大列表。

从阅读关于这个错误的其他问题来看——但没有关于搜索栏的错误——这似乎是{}位置等方面的问题,但再多的修补也无济于事。

编辑1:我创建了一个函数,它接收searchText,然后在Firestore中搜索documentID等于searchText的文档(这些文档应该是唯一的(。

func singleData(searchText: String){
db.collection("Products").whereField("code", isEqualTo: searchText)
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: (err)")
} else {
for document in querySnapshot!.documents {
print("(document.documentID) => (document.data())")
}
}
}
}

ProductList视图中的列表和导航链接已被替换为:

Text("Test").onAppear(){
self.viewModel.singleData(searchText: String)
}

这样做的目的是,如果searchText是一个现有的文档,那么它将把该代码传递到ProductDetail视图,并将用户直接带到那里,从而消除对Lists的需要。它将产品数据打印到控制台,但我在尝试将值返回到视图时遇到了问题,因为它给出了一个void类型错误。

非常感谢。

删除filter中的括号

List(viewModel.product_fire.filter{ searchText.isEmpty ? true : $0.product_name.contains(searchText) }){ product in

但最好是从ViewModel中获得过滤后的对象

最新更新