From b18e0455e717b56053c7247d69a2381aa1dd0f25 Mon Sep 17 00:00:00 2001 From: Mikkel Troels Kongsted Date: Mon, 10 Feb 2025 10:19:21 +0100 Subject: [PATCH] search products --- mobile/lib/pages/all_products_page.dart | 10 +++++++--- mobile/lib/repos/product.dart | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/mobile/lib/pages/all_products_page.dart b/mobile/lib/pages/all_products_page.dart index 5022533..ab512ed 100644 --- a/mobile/lib/pages/all_products_page.dart +++ b/mobile/lib/pages/all_products_page.dart @@ -60,6 +60,7 @@ class AllProductsPage extends StatelessWidget { @override Widget build(BuildContext context) { + final productRepo = Provider.of(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(builder: (_, productRepo, __) { - final products = productRepo.allProducts(); + final products = productRepo.filteredProducts; return ListView.builder( shrinkWrap: true, itemBuilder: (_, idx) => ProductListItem( diff --git a/mobile/lib/repos/product.dart b/mobile/lib/repos/product.dart index bf2ad57..0e93ee8 100644 --- a/mobile/lib/repos/product.dart +++ b/mobile/lib/repos/product.dart @@ -3,8 +3,10 @@ import 'package:flutter/material.dart'; class ProductRepo extends ChangeNotifier { int _nextId = 0; List products = []; + late List 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(