mirror of
https://github.com/Mercantec-GHC/h4-projekt-gruppe-0-sm.git
synced 2025-04-28 00:34:06 +02:00
55 lines
1.4 KiB
Dart
55 lines
1.4 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:mobile/models/product.dart';
|
|
import 'package:mobile/results.dart';
|
|
import 'package:mobile/server/mock_server.dart';
|
|
import 'package:mobile/server/server.dart';
|
|
|
|
class ProductController extends ChangeNotifier {
|
|
final server = MockServer();
|
|
|
|
List<Product> products = [];
|
|
String query = "";
|
|
ProductController() {
|
|
fetchProductsFromServer();
|
|
}
|
|
|
|
Future<void> fetchProductsFromServer() async {
|
|
final res = await server.allProducts();
|
|
switch (res) {
|
|
case Success<List<Product>>(data: final data):
|
|
products = data;
|
|
notifyListeners();
|
|
case Error<List<Product>>():
|
|
return;
|
|
}
|
|
}
|
|
|
|
get filteredProducts {
|
|
if (query.trim().isEmpty) {
|
|
return products;
|
|
}
|
|
return 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();
|
|
}
|
|
|
|
void searchProducts(String query) {
|
|
this.query = query;
|
|
notifyListeners();
|
|
}
|
|
|
|
Result<Product, String> productWithBarcode(String barcode) {
|
|
for (var i = 0; i < products.length; i++) {
|
|
if (products[i].barcode == barcode) {
|
|
return Ok(products[i]);
|
|
}
|
|
}
|
|
return Err("Product with barcode $barcode doesn't exist");
|
|
}
|
|
}
|