search products

This commit is contained in:
Mikkel Troels Kongsted 2025-02-10 10:19:21 +01:00
parent cea1a5f5bd
commit b18e0455e7
2 changed files with 25 additions and 3 deletions

View File

@ -60,6 +60,7 @@ class AllProductsPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final productRepo = Provider.of<ProductRepo>(context);
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
@ -70,8 +71,11 @@ class AllProductsPage extends StatelessWidget {
Expanded(
child: Container(
margin: const EdgeInsets.only(left: 10, right: 10),
child: const TextField(
decoration: InputDecoration(
child: TextField(
onChanged: (query) {
productRepo.searchProducts(query);
},
decoration: const InputDecoration(
label: Text("Search"),
contentPadding: EdgeInsets.only(top: 20))),
),
@ -80,7 +84,7 @@ class AllProductsPage extends StatelessWidget {
),
Expanded(
child: Consumer<ProductRepo>(builder: (_, productRepo, __) {
final products = productRepo.allProducts();
final products = productRepo.filteredProducts;
return ListView.builder(
shrinkWrap: true,
itemBuilder: (_, idx) => ProductListItem(

View File

@ -3,8 +3,10 @@ import 'package:flutter/material.dart';
class ProductRepo extends ChangeNotifier {
int _nextId = 0;
List<Product> products = [];
late List<Product> filteredProducts;
ProductRepo() {
_addAllProducts();
filteredProducts = products;
}
int getNextId() {
@ -15,6 +17,22 @@ class ProductRepo extends ChangeNotifier {
return products;
}
void searchProducts(String query) {
if (query.trim().isEmpty) {
filteredProducts = products;
} else {
filteredProducts = products.where((product) {
final nameLower = product.name.toLowerCase();
final descriptionLower = product.description.toLowerCase();
final searchLower = query.toLowerCase();
return nameLower.contains(searchLower) ||
descriptionLower.contains(searchLower);
}).toList();
}
notifyListeners();
}
void _addAllProducts() {
products = [
Product(