Compare commits

...

3 Commits

Author SHA1 Message Date
Phuoc Nguyen
bffe446694 batch 2025-10-15 18:14:27 +07:00
Phuoc Nguyen
02e5fd4244 add detail, fetch products, categories 2025-10-15 17:46:50 +07:00
Phuoc Nguyen
4038f8e8a6 update products 2025-10-15 16:58:20 +07:00
30 changed files with 2977 additions and 403 deletions

869
claude.md

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,10 @@
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../network/dio_client.dart';
part 'dio_client_provider.g.dart';
/// Provider for DioClient singleton
@Riverpod(keepAlive: true)
DioClient dioClient(Ref ref) {
return DioClient();
}

View File

@@ -0,0 +1,55 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'dio_client_provider.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Provider for DioClient singleton
@ProviderFor(dioClient)
const dioClientProvider = DioClientProvider._();
/// Provider for DioClient singleton
final class DioClientProvider
extends $FunctionalProvider<DioClient, DioClient, DioClient>
with $Provider<DioClient> {
/// Provider for DioClient singleton
const DioClientProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'dioClientProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$dioClientHash();
@$internal
@override
$ProviderElement<DioClient> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
DioClient create(Ref ref) {
return dioClient(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(DioClient value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<DioClient>(value),
);
}
}
String _$dioClientHash() => r'895f0dc2f8d5eab562ad65390e5c6d4a1f722b0d';

View File

@@ -1,3 +1,4 @@
/// Export all core providers /// Export all core providers
export 'network_info_provider.dart'; export 'network_info_provider.dart';
export 'sync_status_provider.dart'; export 'sync_status_provider.dart';
export 'dio_client_provider.dart';

View File

@@ -27,7 +27,7 @@ class EmptyState extends StatelessWidget {
children: [ children: [
Icon( Icon(
icon ?? Icons.inbox_outlined, icon ?? Icons.inbox_outlined,
size: 80, size: 50,
color: Theme.of(context).colorScheme.outline, color: Theme.of(context).colorScheme.outline,
), ),
const SizedBox(height: 24), const SizedBox(height: 24),

View File

@@ -234,7 +234,7 @@ final class AuthProvider extends $NotifierProvider<Auth, AuthState> {
} }
} }
String _$authHash() => r'4b053a7691f573316a8957577dd27a3ed73d89be'; String _$authHash() => r'73c9e7b70799eba2904eb6fc65454332d4146a33';
/// Auth state notifier provider /// Auth state notifier provider

View File

@@ -0,0 +1,51 @@
import '../models/category_model.dart';
import '../../../../core/network/dio_client.dart';
import '../../../../core/constants/api_constants.dart';
import '../../../../core/errors/exceptions.dart';
/// Category remote data source using API
abstract class CategoryRemoteDataSource {
Future<List<CategoryModel>> getAllCategories();
Future<CategoryModel> getCategoryById(String id);
}
class CategoryRemoteDataSourceImpl implements CategoryRemoteDataSource {
final DioClient client;
CategoryRemoteDataSourceImpl(this.client);
@override
Future<List<CategoryModel>> getAllCategories() async {
try {
final response = await client.get(ApiConstants.categories);
// API returns: { success: true, data: [...categories...] }
if (response.data['success'] == true) {
final List<dynamic> data = response.data['data'] ?? [];
return data.map((json) => CategoryModel.fromJson(json)).toList();
} else {
throw ServerException(response.data['message'] ?? 'Failed to fetch categories');
}
} catch (e) {
if (e is ServerException) rethrow;
throw ServerException('Failed to fetch categories: $e');
}
}
@override
Future<CategoryModel> getCategoryById(String id) async {
try {
final response = await client.get(ApiConstants.categoryById(id));
// API returns: { success: true, data: {...category...} }
if (response.data['success'] == true) {
return CategoryModel.fromJson(response.data['data']);
} else {
throw ServerException(response.data['message'] ?? 'Category not found');
}
} catch (e) {
if (e is ServerException) rethrow;
throw ServerException('Failed to fetch category: $e');
}
}
}

View File

@@ -0,0 +1,43 @@
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:hive_ce/hive.dart';
import '../datasources/category_local_datasource.dart';
import '../datasources/category_remote_datasource.dart';
import '../repositories/category_repository_impl.dart';
import '../models/category_model.dart';
import '../../domain/repositories/category_repository.dart';
import '../../../../core/providers/providers.dart';
import '../../../../core/constants/storage_constants.dart';
part 'category_providers.g.dart';
/// Provider for category Hive box
@riverpod
Box<CategoryModel> categoryBox(Ref ref) {
return Hive.box<CategoryModel>(StorageConstants.categoriesBox);
}
/// Provider for category local data source
@riverpod
CategoryLocalDataSource categoryLocalDataSource(Ref ref) {
final box = ref.watch(categoryBoxProvider);
return CategoryLocalDataSourceImpl(box);
}
/// Provider for category remote data source
@riverpod
CategoryRemoteDataSource categoryRemoteDataSource(Ref ref) {
final dioClient = ref.watch(dioClientProvider);
return CategoryRemoteDataSourceImpl(dioClient);
}
/// Provider for category repository
@riverpod
CategoryRepository categoryRepository(Ref ref) {
final localDataSource = ref.watch(categoryLocalDataSourceProvider);
final remoteDataSource = ref.watch(categoryRemoteDataSourceProvider);
return CategoryRepositoryImpl(
localDataSource: localDataSource,
remoteDataSource: remoteDataSource,
);
}

View File

@@ -0,0 +1,220 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'category_providers.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Provider for category Hive box
@ProviderFor(categoryBox)
const categoryBoxProvider = CategoryBoxProvider._();
/// Provider for category Hive box
final class CategoryBoxProvider
extends
$FunctionalProvider<
Box<CategoryModel>,
Box<CategoryModel>,
Box<CategoryModel>
>
with $Provider<Box<CategoryModel>> {
/// Provider for category Hive box
const CategoryBoxProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'categoryBoxProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$categoryBoxHash();
@$internal
@override
$ProviderElement<Box<CategoryModel>> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
Box<CategoryModel> create(Ref ref) {
return categoryBox(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(Box<CategoryModel> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<Box<CategoryModel>>(value),
);
}
}
String _$categoryBoxHash() => r'cbcd3cf6f0673b13a5e0af6dba10ca10f32be70c';
/// Provider for category local data source
@ProviderFor(categoryLocalDataSource)
const categoryLocalDataSourceProvider = CategoryLocalDataSourceProvider._();
/// Provider for category local data source
final class CategoryLocalDataSourceProvider
extends
$FunctionalProvider<
CategoryLocalDataSource,
CategoryLocalDataSource,
CategoryLocalDataSource
>
with $Provider<CategoryLocalDataSource> {
/// Provider for category local data source
const CategoryLocalDataSourceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'categoryLocalDataSourceProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$categoryLocalDataSourceHash();
@$internal
@override
$ProviderElement<CategoryLocalDataSource> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
CategoryLocalDataSource create(Ref ref) {
return categoryLocalDataSource(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(CategoryLocalDataSource value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<CategoryLocalDataSource>(value),
);
}
}
String _$categoryLocalDataSourceHash() =>
r'8d42c0dcfb986dfa0413e4267c4b08f24963ef50';
/// Provider for category remote data source
@ProviderFor(categoryRemoteDataSource)
const categoryRemoteDataSourceProvider = CategoryRemoteDataSourceProvider._();
/// Provider for category remote data source
final class CategoryRemoteDataSourceProvider
extends
$FunctionalProvider<
CategoryRemoteDataSource,
CategoryRemoteDataSource,
CategoryRemoteDataSource
>
with $Provider<CategoryRemoteDataSource> {
/// Provider for category remote data source
const CategoryRemoteDataSourceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'categoryRemoteDataSourceProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$categoryRemoteDataSourceHash();
@$internal
@override
$ProviderElement<CategoryRemoteDataSource> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
CategoryRemoteDataSource create(Ref ref) {
return categoryRemoteDataSource(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(CategoryRemoteDataSource value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<CategoryRemoteDataSource>(value),
);
}
}
String _$categoryRemoteDataSourceHash() =>
r'60294160d6655f1455064fb01016d341570e9a5d';
/// Provider for category repository
@ProviderFor(categoryRepository)
const categoryRepositoryProvider = CategoryRepositoryProvider._();
/// Provider for category repository
final class CategoryRepositoryProvider
extends
$FunctionalProvider<
CategoryRepository,
CategoryRepository,
CategoryRepository
>
with $Provider<CategoryRepository> {
/// Provider for category repository
const CategoryRepositoryProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'categoryRepositoryProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$categoryRepositoryHash();
@$internal
@override
$ProviderElement<CategoryRepository> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
CategoryRepository create(Ref ref) {
return categoryRepository(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(CategoryRepository value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<CategoryRepository>(value),
);
}
}
String _$categoryRepositoryHash() =>
r'256a9f2aa52a1858bbb50a87f2f838c33552ef22';

View File

@@ -2,14 +2,17 @@ import 'package:dartz/dartz.dart';
import '../../domain/entities/category.dart'; import '../../domain/entities/category.dart';
import '../../domain/repositories/category_repository.dart'; import '../../domain/repositories/category_repository.dart';
import '../datasources/category_local_datasource.dart'; import '../datasources/category_local_datasource.dart';
import '../datasources/category_remote_datasource.dart';
import '../../../../core/errors/failures.dart'; import '../../../../core/errors/failures.dart';
import '../../../../core/errors/exceptions.dart'; import '../../../../core/errors/exceptions.dart';
class CategoryRepositoryImpl implements CategoryRepository { class CategoryRepositoryImpl implements CategoryRepository {
final CategoryLocalDataSource localDataSource; final CategoryLocalDataSource localDataSource;
final CategoryRemoteDataSource remoteDataSource;
CategoryRepositoryImpl({ CategoryRepositoryImpl({
required this.localDataSource, required this.localDataSource,
required this.remoteDataSource,
}); });
@override @override
@@ -38,12 +41,13 @@ class CategoryRepositoryImpl implements CategoryRepository {
@override @override
Future<Either<Failure, List<Category>>> syncCategories() async { Future<Either<Failure, List<Category>>> syncCategories() async {
try { try {
// For now, return cached categories final categories = await remoteDataSource.getAllCategories();
// In the future, implement remote sync await localDataSource.cacheCategories(categories);
final categories = await localDataSource.getAllCategories();
return Right(categories.map((model) => model.toEntity()).toList()); return Right(categories.map((model) => model.toEntity()).toList());
} on CacheException catch (e) { } on ServerException catch (e) {
return Left(CacheFailure(e.message)); return Left(ServerFailure(e.message));
} on NetworkException catch (e) {
return Left(NetworkFailure(e.message));
} }
} }
} }

View File

@@ -0,0 +1,166 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../domain/entities/category.dart';
import '../../../products/presentation/providers/products_provider.dart';
import '../../../products/presentation/widgets/product_card.dart';
import '../../../products/presentation/widgets/product_list_item.dart';
/// View mode for products display
enum ViewMode { grid, list }
/// Category detail page showing products in the category
class CategoryDetailPage extends ConsumerStatefulWidget {
final Category category;
const CategoryDetailPage({
super.key,
required this.category,
});
@override
ConsumerState<CategoryDetailPage> createState() => _CategoryDetailPageState();
}
class _CategoryDetailPageState extends ConsumerState<CategoryDetailPage> {
ViewMode _viewMode = ViewMode.grid;
@override
Widget build(BuildContext context) {
final productsAsync = ref.watch(productsProvider);
return Scaffold(
appBar: AppBar(
title: Text(widget.category.name),
actions: [
// View mode toggle
IconButton(
icon: Icon(
_viewMode == ViewMode.grid
? Icons.view_list_rounded
: Icons.grid_view_rounded,
),
onPressed: () {
setState(() {
_viewMode =
_viewMode == ViewMode.grid ? ViewMode.list : ViewMode.grid;
});
},
tooltip: _viewMode == ViewMode.grid
? 'Switch to list view'
: 'Switch to grid view',
),
],
),
body: productsAsync.when(
data: (products) {
// Filter products by category
final categoryProducts = products
.where((product) => product.categoryId == widget.category.id)
.toList();
if (categoryProducts.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.inventory_2_outlined,
size: 64,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
'No products in this category',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 8),
Text(
'Products will appear here once added',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
),
);
}
return RefreshIndicator(
onRefresh: () async {
await ref.read(productsProvider.notifier).syncProducts();
},
child: _viewMode == ViewMode.grid
? _buildGridView(categoryProducts)
: _buildListView(categoryProducts),
);
},
loading: () => const Center(
child: CircularProgressIndicator(),
),
error: (error, stack) => Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error_outline,
size: 64,
color: Theme.of(context).colorScheme.error,
),
const SizedBox(height: 16),
Text(
'Error loading products',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
Text(
error.toString(),
style: Theme.of(context).textTheme.bodySmall,
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
FilledButton.icon(
onPressed: () {
ref.invalidate(productsProvider);
},
icon: const Icon(Icons.refresh),
label: const Text('Retry'),
),
],
),
),
),
);
}
/// Build grid view
Widget _buildGridView(List products) {
return GridView.builder(
padding: const EdgeInsets.all(16),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.75,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
),
itemCount: products.length,
itemBuilder: (context, index) {
return ProductCard(product: products[index]);
},
);
}
/// Build list view
Widget _buildListView(List products) {
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: products.length,
itemBuilder: (context, index) {
return ProductListItem(
product: products[index],
);
},
);
}
}

View File

@@ -1,31 +1,92 @@
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../domain/entities/category.dart'; import '../../domain/entities/category.dart';
import '../../data/providers/category_providers.dart';
import '../../../../core/providers/providers.dart';
part 'categories_provider.g.dart'; part 'categories_provider.g.dart';
/// Provider for categories list /// Provider for categories list with API-first approach
@riverpod @riverpod
class Categories extends _$Categories { class Categories extends _$Categories {
@override @override
Future<List<Category>> build() async { Future<List<Category>> build() async {
// TODO: Implement with repository // API-first: Try to load from API first
return []; final repository = ref.watch(categoryRepositoryProvider);
final networkInfo = ref.watch(networkInfoProvider);
// Check if online
final isConnected = await networkInfo.isConnected;
if (isConnected) {
// Try API first
try {
final syncResult = await repository.syncCategories();
return syncResult.fold(
(failure) {
// API failed, fallback to cache
print('Categories API failed, falling back to cache: ${failure.message}');
return _loadFromCache();
},
(categories) => categories,
);
} catch (e) {
// API error, fallback to cache
print('Categories API error, falling back to cache: $e');
return _loadFromCache();
}
} else {
// Offline, load from cache
print('Offline, loading categories from cache');
return _loadFromCache();
}
} }
/// Load categories from local cache
Future<List<Category>> _loadFromCache() async {
final repository = ref.read(categoryRepositoryProvider);
final result = await repository.getAllCategories();
return result.fold(
(failure) {
print('Categories cache load failed: ${failure.message}');
return <Category>[];
},
(categories) => categories,
);
}
/// Refresh categories from local storage
Future<void> refresh() async { Future<void> refresh() async {
state = const AsyncValue.loading(); state = const AsyncValue.loading();
state = await AsyncValue.guard(() async { state = await AsyncValue.guard(() async {
// Fetch categories from repository final repository = ref.read(categoryRepositoryProvider);
return []; final result = await repository.getAllCategories();
return result.fold(
(failure) => throw Exception(failure.message),
(categories) => categories,
);
}); });
} }
/// Sync categories from API and update local storage
Future<void> syncCategories() async { Future<void> syncCategories() async {
// TODO: Implement sync logic with remote data source final networkInfo = ref.read(networkInfoProvider);
final isConnected = await networkInfo.isConnected;
if (!isConnected) {
throw Exception('No internet connection');
}
state = const AsyncValue.loading(); state = const AsyncValue.loading();
state = await AsyncValue.guard(() async { state = await AsyncValue.guard(() async {
// Sync categories from API final repository = ref.read(categoryRepositoryProvider);
return []; final result = await repository.syncCategories();
return result.fold(
(failure) => throw Exception(failure.message),
(categories) => categories,
);
}); });
} }
} }

View File

@@ -8,15 +8,15 @@ part of 'categories_provider.dart';
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning // ignore_for_file: type=lint, type=warning
/// Provider for categories list /// Provider for categories list with API-first approach
@ProviderFor(Categories) @ProviderFor(Categories)
const categoriesProvider = CategoriesProvider._(); const categoriesProvider = CategoriesProvider._();
/// Provider for categories list /// Provider for categories list with API-first approach
final class CategoriesProvider final class CategoriesProvider
extends $AsyncNotifierProvider<Categories, List<Category>> { extends $AsyncNotifierProvider<Categories, List<Category>> {
/// Provider for categories list /// Provider for categories list with API-first approach
const CategoriesProvider._() const CategoriesProvider._()
: super( : super(
from: null, from: null,
@@ -36,9 +36,9 @@ final class CategoriesProvider
Categories create() => Categories(); Categories create() => Categories();
} }
String _$categoriesHash() => r'aa7afc38a5567b0f42ff05ca23b287baa4780cbe'; String _$categoriesHash() => r'33c33b08f8926e5bbbd112285591c74a3ff0f61c';
/// Provider for categories list /// Provider for categories list with API-first approach
abstract class _$Categories extends $AsyncNotifier<List<Category>> { abstract class _$Categories extends $AsyncNotifier<List<Category>> {
FutureOr<List<Category>> build(); FutureOr<List<Category>> build();

View File

@@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../domain/entities/category.dart'; import '../../domain/entities/category.dart';
import '../pages/category_detail_page.dart';
/// Category card widget /// Category card widget
class CategoryCard extends StatelessWidget { class CategoryCard extends StatelessWidget {
@@ -20,7 +21,13 @@ class CategoryCard extends StatelessWidget {
color: color, color: color,
child: InkWell( child: InkWell(
onTap: () { onTap: () {
// TODO: Filter products by category // Navigate to category detail page
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CategoryDetailPage(category: category),
),
);
}, },
child: Padding( child: Padding(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),

View File

@@ -6,6 +6,7 @@ abstract class ProductLocalDataSource {
Future<List<ProductModel>> getAllProducts(); Future<List<ProductModel>> getAllProducts();
Future<ProductModel?> getProductById(String id); Future<ProductModel?> getProductById(String id);
Future<void> cacheProducts(List<ProductModel> products); Future<void> cacheProducts(List<ProductModel> products);
Future<void> updateProduct(ProductModel product);
Future<void> clearProducts(); Future<void> clearProducts();
} }
@@ -30,6 +31,11 @@ class ProductLocalDataSourceImpl implements ProductLocalDataSource {
await box.putAll(productMap); await box.putAll(productMap);
} }
@override
Future<void> updateProduct(ProductModel product) async {
await box.put(product.id, product);
}
@override @override
Future<void> clearProducts() async { Future<void> clearProducts() async {
await box.clear(); await box.clear();

View File

@@ -1,12 +1,19 @@
import '../models/product_model.dart'; import '../models/product_model.dart';
import '../../../../core/network/dio_client.dart'; import '../../../../core/network/dio_client.dart';
import '../../../../core/constants/api_constants.dart'; import '../../../../core/constants/api_constants.dart';
import '../../../../core/errors/exceptions.dart';
/// Product remote data source using API /// Product remote data source using API
abstract class ProductRemoteDataSource { abstract class ProductRemoteDataSource {
Future<List<ProductModel>> getAllProducts(); Future<List<ProductModel>> getAllProducts({
int page = 1,
int limit = 20,
String? categoryId,
String? search,
});
Future<ProductModel> getProductById(String id); Future<ProductModel> getProductById(String id);
Future<List<ProductModel>> searchProducts(String query); Future<List<ProductModel>> searchProducts(String query, {int page = 1, int limit = 20});
Future<List<ProductModel>> getProductsByCategory(String categoryId, {int page = 1, int limit = 20});
} }
class ProductRemoteDataSourceImpl implements ProductRemoteDataSource { class ProductRemoteDataSourceImpl implements ProductRemoteDataSource {
@@ -15,25 +22,107 @@ class ProductRemoteDataSourceImpl implements ProductRemoteDataSource {
ProductRemoteDataSourceImpl(this.client); ProductRemoteDataSourceImpl(this.client);
@override @override
Future<List<ProductModel>> getAllProducts() async { Future<List<ProductModel>> getAllProducts({
final response = await client.get(ApiConstants.products); int page = 1,
final List<dynamic> data = response.data['products'] ?? []; int limit = 20,
String? categoryId,
String? search,
}) async {
try {
final queryParams = <String, dynamic>{
'page': page,
'limit': limit,
};
if (categoryId != null) {
queryParams['categoryId'] = categoryId;
}
if (search != null && search.isNotEmpty) {
queryParams['search'] = search;
}
final response = await client.get(
ApiConstants.products,
queryParameters: queryParams,
);
// API returns: { success: true, data: [...products...], meta: {...} }
if (response.data['success'] == true) {
final List<dynamic> data = response.data['data'] ?? [];
return data.map((json) => ProductModel.fromJson(json)).toList(); return data.map((json) => ProductModel.fromJson(json)).toList();
} else {
throw ServerException(response.data['message'] ?? 'Failed to fetch products');
}
} catch (e) {
if (e is ServerException) rethrow;
throw ServerException('Failed to fetch products: $e');
}
} }
@override @override
Future<ProductModel> getProductById(String id) async { Future<ProductModel> getProductById(String id) async {
try {
final response = await client.get(ApiConstants.productById(id)); final response = await client.get(ApiConstants.productById(id));
return ProductModel.fromJson(response.data);
// API returns: { success: true, data: {...product...} }
if (response.data['success'] == true) {
return ProductModel.fromJson(response.data['data']);
} else {
throw ServerException(response.data['message'] ?? 'Product not found');
}
} catch (e) {
if (e is ServerException) rethrow;
throw ServerException('Failed to fetch product: $e');
}
} }
@override @override
Future<List<ProductModel>> searchProducts(String query) async { Future<List<ProductModel>> searchProducts(String query, {int page = 1, int limit = 20}) async {
try {
final response = await client.get( final response = await client.get(
ApiConstants.searchProducts, ApiConstants.searchProducts,
queryParameters: {'q': query}, queryParameters: {
'q': query,
'page': page,
'limit': limit,
},
); );
final List<dynamic> data = response.data['products'] ?? [];
// API returns: { success: true, data: [...products...], meta: {...} }
if (response.data['success'] == true) {
final List<dynamic> data = response.data['data'] ?? [];
return data.map((json) => ProductModel.fromJson(json)).toList(); return data.map((json) => ProductModel.fromJson(json)).toList();
} else {
throw ServerException(response.data['message'] ?? 'Failed to search products');
}
} catch (e) {
if (e is ServerException) rethrow;
throw ServerException('Failed to search products: $e');
}
}
@override
Future<List<ProductModel>> getProductsByCategory(String categoryId, {int page = 1, int limit = 20}) async {
try {
final response = await client.get(
ApiConstants.productsByCategory(categoryId),
queryParameters: {
'page': page,
'limit': limit,
},
);
// API returns: { success: true, data: [...products...], meta: {...} }
if (response.data['success'] == true) {
final List<dynamic> data = response.data['data'] ?? [];
return data.map((json) => ProductModel.fromJson(json)).toList();
} else {
throw ServerException(response.data['message'] ?? 'Failed to fetch products by category');
}
} catch (e) {
if (e is ServerException) rethrow;
throw ServerException('Failed to fetch products by category: $e');
}
} }
} }

View File

@@ -86,12 +86,12 @@ class ProductModel extends HiveObject {
return ProductModel( return ProductModel(
id: json['id'] as String, id: json['id'] as String,
name: json['name'] as String, name: json['name'] as String,
description: json['description'] as String, description: json['description'] as String? ?? '',
price: (json['price'] as num).toDouble(), price: (json['price'] as num).toDouble(),
imageUrl: json['imageUrl'] as String?, imageUrl: json['imageUrl'] as String?,
categoryId: json['categoryId'] as String, categoryId: json['categoryId'] as String,
stockQuantity: json['stockQuantity'] as int, stockQuantity: json['stockQuantity'] as int? ?? 0,
isAvailable: json['isAvailable'] as bool, isAvailable: json['isAvailable'] as bool? ?? true,
createdAt: DateTime.parse(json['createdAt'] as String), createdAt: DateTime.parse(json['createdAt'] as String),
updatedAt: DateTime.parse(json['updatedAt'] as String), updatedAt: DateTime.parse(json['updatedAt'] as String),
); );

View File

@@ -0,0 +1,43 @@
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:hive_ce/hive.dart';
import '../datasources/product_local_datasource.dart';
import '../datasources/product_remote_datasource.dart';
import '../repositories/product_repository_impl.dart';
import '../models/product_model.dart';
import '../../domain/repositories/product_repository.dart';
import '../../../../core/providers/providers.dart';
import '../../../../core/constants/storage_constants.dart';
part 'product_providers.g.dart';
/// Provider for product Hive box
@riverpod
Box<ProductModel> productBox(Ref ref) {
return Hive.box<ProductModel>(StorageConstants.productsBox);
}
/// Provider for product local data source
@riverpod
ProductLocalDataSource productLocalDataSource(Ref ref) {
final box = ref.watch(productBoxProvider);
return ProductLocalDataSourceImpl(box);
}
/// Provider for product remote data source
@riverpod
ProductRemoteDataSource productRemoteDataSource(Ref ref) {
final dioClient = ref.watch(dioClientProvider);
return ProductRemoteDataSourceImpl(dioClient);
}
/// Provider for product repository
@riverpod
ProductRepository productRepository(Ref ref) {
final localDataSource = ref.watch(productLocalDataSourceProvider);
final remoteDataSource = ref.watch(productRemoteDataSourceProvider);
return ProductRepositoryImpl(
localDataSource: localDataSource,
remoteDataSource: remoteDataSource,
);
}

View File

@@ -0,0 +1,219 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'product_providers.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Provider for product Hive box
@ProviderFor(productBox)
const productBoxProvider = ProductBoxProvider._();
/// Provider for product Hive box
final class ProductBoxProvider
extends
$FunctionalProvider<
Box<ProductModel>,
Box<ProductModel>,
Box<ProductModel>
>
with $Provider<Box<ProductModel>> {
/// Provider for product Hive box
const ProductBoxProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'productBoxProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$productBoxHash();
@$internal
@override
$ProviderElement<Box<ProductModel>> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
Box<ProductModel> create(Ref ref) {
return productBox(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(Box<ProductModel> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<Box<ProductModel>>(value),
);
}
}
String _$productBoxHash() => r'68cd21ea28cfc716f34daef17849a0393cdb2b80';
/// Provider for product local data source
@ProviderFor(productLocalDataSource)
const productLocalDataSourceProvider = ProductLocalDataSourceProvider._();
/// Provider for product local data source
final class ProductLocalDataSourceProvider
extends
$FunctionalProvider<
ProductLocalDataSource,
ProductLocalDataSource,
ProductLocalDataSource
>
with $Provider<ProductLocalDataSource> {
/// Provider for product local data source
const ProductLocalDataSourceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'productLocalDataSourceProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$productLocalDataSourceHash();
@$internal
@override
$ProviderElement<ProductLocalDataSource> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
ProductLocalDataSource create(Ref ref) {
return productLocalDataSource(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(ProductLocalDataSource value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<ProductLocalDataSource>(value),
);
}
}
String _$productLocalDataSourceHash() =>
r'ef4673055777e8dc8a8419a80548b319789d99f9';
/// Provider for product remote data source
@ProviderFor(productRemoteDataSource)
const productRemoteDataSourceProvider = ProductRemoteDataSourceProvider._();
/// Provider for product remote data source
final class ProductRemoteDataSourceProvider
extends
$FunctionalProvider<
ProductRemoteDataSource,
ProductRemoteDataSource,
ProductRemoteDataSource
>
with $Provider<ProductRemoteDataSource> {
/// Provider for product remote data source
const ProductRemoteDataSourceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'productRemoteDataSourceProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$productRemoteDataSourceHash();
@$internal
@override
$ProviderElement<ProductRemoteDataSource> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
ProductRemoteDataSource create(Ref ref) {
return productRemoteDataSource(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(ProductRemoteDataSource value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<ProductRemoteDataSource>(value),
);
}
}
String _$productRemoteDataSourceHash() =>
r'954798907bb0c9baade27b84eaba612a5dec8f68';
/// Provider for product repository
@ProviderFor(productRepository)
const productRepositoryProvider = ProductRepositoryProvider._();
/// Provider for product repository
final class ProductRepositoryProvider
extends
$FunctionalProvider<
ProductRepository,
ProductRepository,
ProductRepository
>
with $Provider<ProductRepository> {
/// Provider for product repository
const ProductRepositoryProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'productRepositoryProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$productRepositoryHash();
@$internal
@override
$ProviderElement<ProductRepository> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
ProductRepository create(Ref ref) {
return productRepository(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(ProductRepository value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<ProductRepository>(value),
);
}
}
String _$productRepositoryHash() => r'7c5c5b274ce459add6449c29be822ea04503d3dc';

View File

@@ -0,0 +1,372 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../domain/entities/product.dart';
import '../../data/models/product_model.dart';
import '../providers/products_provider.dart';
import '../../data/providers/product_providers.dart';
/// Batch update page for updating multiple products
class BatchUpdatePage extends ConsumerStatefulWidget {
final List<Product> selectedProducts;
const BatchUpdatePage({
super.key,
required this.selectedProducts,
});
@override
ConsumerState<BatchUpdatePage> createState() => _BatchUpdatePageState();
}
class _BatchUpdatePageState extends ConsumerState<BatchUpdatePage> {
final _formKey = GlobalKey<FormState>();
late List<ProductUpdateData> _productsData;
bool _isLoading = false;
@override
void initState() {
super.initState();
// Initialize update data for each product
_productsData = widget.selectedProducts.map((product) {
return ProductUpdateData(
product: product,
priceController: TextEditingController(text: product.price.toStringAsFixed(2)),
stock: product.stockQuantity,
);
}).toList();
}
@override
void dispose() {
for (var data in _productsData) {
data.priceController.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Edit ${widget.selectedProducts.length} Products'),
actions: [
if (_isLoading)
const Center(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
),
],
),
body: Form(
key: _formKey,
child: Column(
children: [
// Header
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
color: Theme.of(context).colorScheme.primaryContainer,
child: Row(
children: [
Expanded(
child: Text(
'Product',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
),
),
SizedBox(
width: 70,
child: Text(
'Price',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
),
),
const SizedBox(width: 4),
SizedBox(
width: 80,
child: Text(
'Stock',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.onPrimaryContainer,
),
),
),
],
),
),
// Products list
Expanded(
child: ListView.separated(
padding: const EdgeInsets.all(8),
itemCount: _productsData.length,
separatorBuilder: (context, index) => const SizedBox(height: 8),
itemBuilder: (context, index) {
return _buildProductItem(_productsData[index]);
},
),
),
// Action buttons
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 4,
offset: const Offset(0, -2),
),
],
),
child: SafeArea(
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: _isLoading ? null : () => Navigator.pop(context),
child: const Text('Cancel'),
),
),
const SizedBox(width: 16),
Expanded(
child: FilledButton(
onPressed: _isLoading ? null : _handleSave,
child: const Text('Save Changes'),
),
),
],
),
),
),
],
),
),
);
}
/// Build product item
Widget _buildProductItem(ProductUpdateData data) {
return Card(
margin: EdgeInsets.zero,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Product info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
data.product.name,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontWeight: FontWeight.w600,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
Text(
'\$${data.product.price.toStringAsFixed(2)}',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
),
),
const SizedBox(width: 4),
// Price field
SizedBox(
width: 70,
child: TextFormField(
controller: data.priceController,
decoration: const InputDecoration(
prefixText: '\$',
isDense: true,
contentPadding: EdgeInsets.symmetric(horizontal: 6, vertical: 6),
border: OutlineInputBorder(),
),
style: Theme.of(context).textTheme.bodySmall,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}')),
],
validator: (value) {
if (value == null || value.isEmpty) return '';
final number = double.tryParse(value);
if (number == null || number < 0) return '';
return null;
},
),
),
const SizedBox(width: 4),
// Stock controls
Row(
mainAxisSize: MainAxisSize.min,
children: [
// Decrease button
InkWell(
onTap: data.stock > 0
? () {
setState(() {
data.stock--;
});
}
: null,
child: Container(
padding: const EdgeInsets.all(6),
child: Icon(
Icons.remove,
size: 18,
color: data.stock > 0
? Theme.of(context).colorScheme.primary
: Theme.of(context).disabledColor,
),
),
),
// Stock count
Container(
constraints: const BoxConstraints(minWidth: 35),
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.outline,
),
borderRadius: BorderRadius.circular(4),
),
child: Text(
'${data.stock}',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
),
// Increase button
InkWell(
onTap: () {
setState(() {
data.stock++;
});
},
child: Container(
padding: const EdgeInsets.all(6),
child: Icon(
Icons.add,
size: 18,
color: Theme.of(context).colorScheme.primary,
),
),
),
],
),
],
),
),
);
}
/// Handle save
Future<void> _handleSave() async {
if (!_formKey.currentState!.validate()) {
return;
}
setState(() {
_isLoading = true;
});
try {
final localDataSource = ref.read(productLocalDataSourceProvider);
// Update each product
for (var data in _productsData) {
final newPrice = double.parse(data.priceController.text);
final newStock = data.stock;
// Create updated product model
final updatedProduct = ProductModel(
id: data.product.id,
name: data.product.name,
description: data.product.description,
price: newPrice,
imageUrl: data.product.imageUrl,
categoryId: data.product.categoryId,
stockQuantity: newStock,
isAvailable: data.product.isAvailable,
createdAt: data.product.createdAt,
updatedAt: DateTime.now(),
);
// Update in local storage
await localDataSource.updateProduct(updatedProduct);
}
// Refresh products provider
ref.invalidate(productsProvider);
if (mounted) {
Navigator.pop(context);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'${_productsData.length} product${_productsData.length == 1 ? '' : 's'} updated successfully',
),
behavior: SnackBarBehavior.floating,
backgroundColor: Colors.green,
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error updating products: $e'),
behavior: SnackBarBehavior.floating,
backgroundColor: Colors.red,
),
);
}
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
}
/// Product update data class
class ProductUpdateData {
final Product product;
final TextEditingController priceController;
int stock;
ProductUpdateData({
required this.product,
required this.priceController,
required this.stock,
});
}

View File

@@ -0,0 +1,419 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:intl/intl.dart';
import '../../domain/entities/product.dart';
import '../../../categories/presentation/providers/categories_provider.dart';
import '../../../../shared/widgets/price_display.dart';
/// Product detail page showing full product information
class ProductDetailPage extends ConsumerWidget {
final Product product;
const ProductDetailPage({
super.key,
required this.product,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final categoriesAsync = ref.watch(categoriesProvider);
// Find category name
final categoryName = categoriesAsync.whenOrNull(
data: (categories) {
final category = categories.firstWhere(
(cat) => cat.id == product.categoryId,
orElse: () => categories.first,
);
return category.name;
},
);
return Scaffold(
appBar: AppBar(
title: const Text('Product Details'),
actions: [
IconButton(
icon: const Icon(Icons.edit),
onPressed: () {
// TODO: Navigate to product edit page
},
tooltip: 'Edit product',
),
],
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Product Image
_buildProductImage(context),
// Product Info Section
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Product Name
Text(
product.name,
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
// Category Badge
if (categoryName != null)
Chip(
avatar: const Icon(Icons.category, size: 16),
label: Text(categoryName),
backgroundColor:
Theme.of(context).colorScheme.primaryContainer,
),
const SizedBox(height: 16),
// Price
Row(
children: [
Text(
'Price:',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(width: 8),
PriceDisplay(
price: product.price,
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.primary,
),
),
],
),
const SizedBox(height: 24),
// Stock Information
_buildStockSection(context),
const SizedBox(height: 24),
// Description Section
_buildDescriptionSection(context),
const SizedBox(height: 24),
// Additional Information
_buildAdditionalInfo(context),
const SizedBox(height: 24),
// Action Buttons
_buildActionButtons(context),
],
),
),
],
),
),
);
}
/// Build product image section
Widget _buildProductImage(BuildContext context) {
return Hero(
tag: 'product-${product.id}',
child: Container(
width: double.infinity,
height: 300,
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: product.imageUrl != null
? CachedNetworkImage(
imageUrl: product.imageUrl!,
fit: BoxFit.cover,
placeholder: (context, url) => const Center(
child: CircularProgressIndicator(),
),
errorWidget: (context, url, error) => Center(
child: Icon(
Icons.image_not_supported,
size: 64,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
)
: Center(
child: Icon(
Icons.inventory_2_outlined,
size: 64,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
);
}
/// Build stock information section
Widget _buildStockSection(BuildContext context) {
final stockColor = _getStockColor(context);
final stockStatus = _getStockStatus();
return Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
Icons.inventory,
color: stockColor,
),
const SizedBox(width: 8),
Text(
'Stock Information',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Quantity',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 4),
Text(
'${product.stockQuantity} units',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
],
),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
decoration: BoxDecoration(
color: stockColor,
borderRadius: BorderRadius.circular(20),
),
child: Text(
stockStatus,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
],
),
const SizedBox(height: 12),
Row(
children: [
Icon(
product.isAvailable ? Icons.check_circle : Icons.cancel,
size: 16,
color: product.isAvailable ? Colors.green : Colors.red,
),
const SizedBox(width: 8),
Text(
product.isAvailable ? 'Available for sale' : 'Not available',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: product.isAvailable ? Colors.green : Colors.red,
fontWeight: FontWeight.w600,
),
),
],
),
],
),
),
);
}
/// Build description section
Widget _buildDescriptionSection(BuildContext context) {
if (product.description.isEmpty) {
return const SizedBox.shrink();
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Description',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
product.description,
style: Theme.of(context).textTheme.bodyLarge,
),
],
);
}
/// Build additional information section
Widget _buildAdditionalInfo(BuildContext context) {
final dateFormat = DateFormat('MMM dd, yyyy');
return Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Additional Information',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 12),
_buildInfoRow(
context,
icon: Icons.fingerprint,
label: 'Product ID',
value: product.id,
),
const Divider(height: 24),
_buildInfoRow(
context,
icon: Icons.calendar_today,
label: 'Created',
value: dateFormat.format(product.createdAt),
),
const Divider(height: 24),
_buildInfoRow(
context,
icon: Icons.update,
label: 'Last Updated',
value: dateFormat.format(product.updatedAt),
),
],
),
),
);
}
/// Build info row
Widget _buildInfoRow(
BuildContext context, {
required IconData icon,
required String label,
required String value,
}) {
return Row(
children: [
Icon(
icon,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 2),
Text(
value,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w500,
),
),
],
),
),
],
);
}
/// Build action buttons
Widget _buildActionButtons(BuildContext context) {
return Column(
children: [
// Add to Cart Button
SizedBox(
width: double.infinity,
child: FilledButton.icon(
onPressed: product.isAvailable && product.stockQuantity > 0
? () {
// TODO: Add to cart functionality
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('${product.name} added to cart'),
behavior: SnackBarBehavior.floating,
),
);
}
: null,
icon: const Icon(Icons.shopping_cart),
label: const Text('Add to Cart'),
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
),
),
const SizedBox(height: 12),
// Stock Adjustment Button
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: () {
// TODO: Navigate to stock adjustment
},
icon: const Icon(Icons.inventory_2),
label: const Text('Adjust Stock'),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
),
),
],
);
}
/// Get stock color based on quantity
Color _getStockColor(BuildContext context) {
if (product.stockQuantity == 0) {
return Colors.red;
} else if (product.stockQuantity < 5) {
return Colors.orange;
} else {
return Colors.green;
}
}
/// Get stock status text
String _getStockStatus() {
if (product.stockQuantity == 0) {
return 'Out of Stock';
} else if (product.stockQuantity < 5) {
return 'Low Stock';
} else {
return 'In Stock';
}
}
}

View File

@@ -2,13 +2,19 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../widgets/product_grid.dart'; import '../widgets/product_grid.dart';
import '../widgets/product_search_bar.dart'; import '../widgets/product_search_bar.dart';
import '../widgets/product_list_item.dart';
import '../widgets/product_card.dart';
import '../providers/products_provider.dart'; import '../providers/products_provider.dart';
import '../providers/selected_category_provider.dart' as product_providers; import '../providers/selected_category_provider.dart' as product_providers;
import '../providers/filtered_products_provider.dart'; import '../providers/filtered_products_provider.dart';
import '../../domain/entities/product.dart'; import '../../domain/entities/product.dart';
import '../../../categories/presentation/providers/categories_provider.dart'; import '../../../categories/presentation/providers/categories_provider.dart';
import 'batch_update_page.dart';
/// Products page - displays all products in a grid /// View mode for products display
enum ViewMode { grid, list }
/// Products page - displays all products in a grid or list
class ProductsPage extends ConsumerStatefulWidget { class ProductsPage extends ConsumerStatefulWidget {
const ProductsPage({super.key}); const ProductsPage({super.key});
@@ -18,6 +24,11 @@ class ProductsPage extends ConsumerStatefulWidget {
class _ProductsPageState extends ConsumerState<ProductsPage> { class _ProductsPageState extends ConsumerState<ProductsPage> {
ProductSortOption _sortOption = ProductSortOption.nameAsc; ProductSortOption _sortOption = ProductSortOption.nameAsc;
ViewMode _viewMode = ViewMode.grid;
// Multi-select mode
bool _isSelectionMode = false;
final Set<String> _selectedProductIds = {};
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -25,6 +36,13 @@ class _ProductsPageState extends ConsumerState<ProductsPage> {
final selectedCategory = ref.watch(product_providers.selectedCategoryProvider); final selectedCategory = ref.watch(product_providers.selectedCategoryProvider);
final productsAsync = ref.watch(productsProvider); final productsAsync = ref.watch(productsProvider);
// Debug: Log product loading state
productsAsync.whenOrNull(
data: (products) => debugPrint('Products loaded: ${products.length} items'),
loading: () => debugPrint('Products loading...'),
error: (error, stack) => debugPrint('Products error: $error'),
);
// Get filtered products from the provider // Get filtered products from the provider
final filteredProducts = productsAsync.when( final filteredProducts = productsAsync.when(
data: (products) => products, data: (products) => products,
@@ -34,8 +52,99 @@ class _ProductsPageState extends ConsumerState<ProductsPage> {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Products'), leading: _isSelectionMode
? IconButton(
icon: const Icon(Icons.close),
onPressed: () {
setState(() {
_isSelectionMode = false;
_selectedProductIds.clear();
});
},
)
: null,
title: _isSelectionMode
? Text('${_selectedProductIds.length} selected')
: const Text('Products'),
actions: [ actions: [
if (_isSelectionMode) ...[
// Select All / Deselect All
IconButton(
icon: Icon(
_selectedProductIds.length == filteredProducts.length
? Icons.deselect
: Icons.select_all,
),
onPressed: () {
setState(() {
if (_selectedProductIds.length == filteredProducts.length) {
_selectedProductIds.clear();
} else {
_selectedProductIds.addAll(
filteredProducts.map((p) => p.id),
);
}
});
},
tooltip: _selectedProductIds.length == filteredProducts.length
? 'Deselect all'
: 'Select all',
),
// Batch Update button
IconButton(
icon: const Icon(Icons.edit),
onPressed: _selectedProductIds.isEmpty
? null
: () {
final selectedProducts = filteredProducts
.where((p) => _selectedProductIds.contains(p.id))
.toList();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BatchUpdatePage(
selectedProducts: selectedProducts,
),
),
).then((_) {
setState(() {
_isSelectionMode = false;
_selectedProductIds.clear();
});
});
},
tooltip: 'Batch update',
),
] else ...[
// Multi-select mode button
IconButton(
icon: const Icon(Icons.checklist),
onPressed: filteredProducts.isEmpty
? null
: () {
setState(() {
_isSelectionMode = true;
});
},
tooltip: 'Select products',
),
// View mode toggle
IconButton(
icon: Icon(
_viewMode == ViewMode.grid
? Icons.view_list_rounded
: Icons.grid_view_rounded,
),
onPressed: () {
setState(() {
_viewMode =
_viewMode == ViewMode.grid ? ViewMode.list : ViewMode.grid;
});
},
tooltip: _viewMode == ViewMode.grid
? 'Switch to list view'
: 'Switch to grid view',
),
// Sort button // Sort button
PopupMenuButton<ProductSortOption>( PopupMenuButton<ProductSortOption>(
icon: const Icon(Icons.sort), icon: const Icon(Icons.sort),
@@ -109,6 +218,7 @@ class _ProductsPageState extends ConsumerState<ProductsPage> {
], ],
), ),
], ],
],
bottom: PreferredSize( bottom: PreferredSize(
preferredSize: const Size.fromHeight(120), preferredSize: const Size.fromHeight(120),
child: Column( child: Column(
@@ -168,9 +278,11 @@ class _ProductsPageState extends ConsumerState<ProductsPage> {
), ),
), ),
), ),
body: RefreshIndicator( body: productsAsync.when(
data: (products) => RefreshIndicator(
onRefresh: () async { onRefresh: () async {
await ref.refresh(productsProvider.future); // Force sync with API
await ref.read(productsProvider.notifier).syncProducts();
await ref.refresh(categoriesProvider.future); await ref.refresh(categoriesProvider.future);
}, },
child: Column( child: Column(
@@ -186,15 +298,208 @@ class _ProductsPageState extends ConsumerState<ProductsPage> {
), ),
), ),
), ),
// Product grid // Product grid or list
Expanded( Expanded(
child: ProductGrid( child: _viewMode == ViewMode.grid
sortOption: _sortOption, ? _buildGridView()
), : _buildListView(),
), ),
], ],
), ),
), ),
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, stack) => Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, size: 48, color: Colors.red),
const SizedBox(height: 16),
Text('Error loading products: $error'),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => ref.refresh(productsProvider),
child: const Text('Retry'),
),
],
),
),
),
); );
} }
/// Build grid view for products
Widget _buildGridView() {
if (_isSelectionMode) {
final filteredProducts = ref.watch(filteredProductsProvider);
final sortedProducts = _sortProducts(filteredProducts, _sortOption);
if (sortedProducts.isEmpty) {
return _buildEmptyState();
}
return GridView.builder(
padding: const EdgeInsets.all(16),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.75,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
),
itemCount: sortedProducts.length,
itemBuilder: (context, index) {
final product = sortedProducts[index];
final isSelected = _selectedProductIds.contains(product.id);
return GestureDetector(
onTap: () {
setState(() {
if (isSelected) {
_selectedProductIds.remove(product.id);
} else {
_selectedProductIds.add(product.id);
}
});
},
child: Stack(
children: [
ProductCard(product: product),
Positioned(
top: 8,
right: 8,
child: Container(
decoration: BoxDecoration(
color: isSelected
? Theme.of(context).colorScheme.primary
: Colors.white,
shape: BoxShape.circle,
border: Border.all(
color: isSelected
? Theme.of(context).colorScheme.primary
: Colors.grey,
width: 2,
),
),
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Icon(
isSelected ? Icons.check : null,
size: 16,
color: Colors.white,
),
),
),
),
],
),
);
},
);
}
return ProductGrid(sortOption: _sortOption);
}
/// Build list view for products
Widget _buildListView() {
final filteredProducts = ref.watch(filteredProductsProvider);
final sortedProducts = _sortProducts(filteredProducts, _sortOption);
if (sortedProducts.isEmpty) {
return _buildEmptyState();
}
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: sortedProducts.length,
itemBuilder: (context, index) {
final product = sortedProducts[index];
if (_isSelectionMode) {
final isSelected = _selectedProductIds.contains(product.id);
return CheckboxListTile(
value: isSelected,
onChanged: (value) {
setState(() {
if (value == true) {
_selectedProductIds.add(product.id);
} else {
_selectedProductIds.remove(product.id);
}
});
},
secondary: SizedBox(
width: 60,
height: 60,
child: ProductCard(product: product),
),
title: Text(product.name),
subtitle: Text('\$${product.price.toStringAsFixed(2)} • Stock: ${product.stockQuantity}'),
);
}
return ProductListItem(product: product);
},
);
}
/// Build empty state
Widget _buildEmptyState() {
return const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.inventory_2_outlined,
size: 64,
color: Colors.grey,
),
SizedBox(height: 16),
Text(
'No products found',
style: TextStyle(
fontSize: 16,
color: Colors.grey,
),
),
SizedBox(height: 8),
Text(
'Try adjusting your filters',
style: TextStyle(
fontSize: 14,
color: Colors.grey,
),
),
],
),
);
}
/// Sort products based on selected option
List<Product> _sortProducts(List<Product> products, ProductSortOption option) {
final sorted = List<Product>.from(products);
switch (option) {
case ProductSortOption.nameAsc:
sorted.sort((a, b) => a.name.compareTo(b.name));
break;
case ProductSortOption.nameDesc:
sorted.sort((a, b) => b.name.compareTo(a.name));
break;
case ProductSortOption.priceAsc:
sorted.sort((a, b) => a.price.compareTo(b.price));
break;
case ProductSortOption.priceDesc:
sorted.sort((a, b) => b.price.compareTo(a.price));
break;
case ProductSortOption.newest:
sorted.sort((a, b) => b.createdAt.compareTo(a.createdAt));
break;
case ProductSortOption.oldest:
sorted.sort((a, b) => a.createdAt.compareTo(b.createdAt));
break;
}
return sorted;
}
} }

View File

@@ -1,32 +1,92 @@
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../domain/entities/product.dart'; import '../../domain/entities/product.dart';
import '../../data/providers/product_providers.dart';
import '../../../../core/providers/providers.dart';
part 'products_provider.g.dart'; part 'products_provider.g.dart';
/// Provider for products list /// Provider for products list with API-first approach
@riverpod @riverpod
class Products extends _$Products { class Products extends _$Products {
@override @override
Future<List<Product>> build() async { Future<List<Product>> build() async {
// TODO: Implement with repository // API-first: Try to load from API first
return []; final repository = ref.watch(productRepositoryProvider);
final networkInfo = ref.watch(networkInfoProvider);
// Check if online
final isConnected = await networkInfo.isConnected;
if (isConnected) {
// Try API first
try {
final syncResult = await repository.syncProducts();
return syncResult.fold(
(failure) {
// API failed, fallback to cache
print('API failed, falling back to cache: ${failure.message}');
return _loadFromCache();
},
(products) => products,
);
} catch (e) {
// API error, fallback to cache
print('API error, falling back to cache: $e');
return _loadFromCache();
}
} else {
// Offline, load from cache
print('Offline, loading from cache');
return _loadFromCache();
}
} }
/// Load products from local cache
Future<List<Product>> _loadFromCache() async {
final repository = ref.read(productRepositoryProvider);
final result = await repository.getAllProducts();
return result.fold(
(failure) {
print('Cache load failed: ${failure.message}');
return <Product>[];
},
(products) => products,
);
}
/// Refresh products from local storage
Future<void> refresh() async { Future<void> refresh() async {
// TODO: Implement refresh logic
state = const AsyncValue.loading(); state = const AsyncValue.loading();
state = await AsyncValue.guard(() async { state = await AsyncValue.guard(() async {
// Fetch products from repository final repository = ref.read(productRepositoryProvider);
return []; final result = await repository.getAllProducts();
return result.fold(
(failure) => throw Exception(failure.message),
(products) => products,
);
}); });
} }
/// Sync products from API and update local storage
Future<void> syncProducts() async { Future<void> syncProducts() async {
// TODO: Implement sync logic with remote data source final networkInfo = ref.read(networkInfoProvider);
final isConnected = await networkInfo.isConnected;
if (!isConnected) {
throw Exception('No internet connection');
}
state = const AsyncValue.loading(); state = const AsyncValue.loading();
state = await AsyncValue.guard(() async { state = await AsyncValue.guard(() async {
// Sync products from API final repository = ref.read(productRepositoryProvider);
return []; final result = await repository.syncProducts();
return result.fold(
(failure) => throw Exception(failure.message),
(products) => products,
);
}); });
} }
} }
@@ -41,17 +101,3 @@ class SearchQuery extends _$SearchQuery {
state = query; state = query;
} }
} }
/// Provider for filtered products
@riverpod
List<Product> filteredProducts(Ref ref) {
final products = ref.watch(productsProvider).value ?? [];
final query = ref.watch(searchQueryProvider);
if (query.isEmpty) return products;
return products.where((p) =>
p.name.toLowerCase().contains(query.toLowerCase()) ||
p.description.toLowerCase().contains(query.toLowerCase())
).toList();
}

View File

@@ -8,15 +8,15 @@ part of 'products_provider.dart';
// GENERATED CODE - DO NOT MODIFY BY HAND // GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning // ignore_for_file: type=lint, type=warning
/// Provider for products list /// Provider for products list with API-first approach
@ProviderFor(Products) @ProviderFor(Products)
const productsProvider = ProductsProvider._(); const productsProvider = ProductsProvider._();
/// Provider for products list /// Provider for products list with API-first approach
final class ProductsProvider final class ProductsProvider
extends $AsyncNotifierProvider<Products, List<Product>> { extends $AsyncNotifierProvider<Products, List<Product>> {
/// Provider for products list /// Provider for products list with API-first approach
const ProductsProvider._() const ProductsProvider._()
: super( : super(
from: null, from: null,
@@ -36,9 +36,9 @@ final class ProductsProvider
Products create() => Products(); Products create() => Products();
} }
String _$productsHash() => r'9e1d3aaa1d9cf0b4ff03fdfaf4512a7a15336d51'; String _$productsHash() => r'0ff8c2de46bb4b1e29678cc811ec121c9fb4c8eb';
/// Provider for products list /// Provider for products list with API-first approach
abstract class _$Products extends $AsyncNotifier<List<Product>> { abstract class _$Products extends $AsyncNotifier<List<Product>> {
FutureOr<List<Product>> build(); FutureOr<List<Product>> build();
@@ -116,49 +116,3 @@ abstract class _$SearchQuery extends $Notifier<String> {
element.handleValue(ref, created); element.handleValue(ref, created);
} }
} }
/// Provider for filtered products
@ProviderFor(filteredProducts)
const filteredProductsProvider = FilteredProductsProvider._();
/// Provider for filtered products
final class FilteredProductsProvider
extends $FunctionalProvider<List<Product>, List<Product>, List<Product>>
with $Provider<List<Product>> {
/// Provider for filtered products
const FilteredProductsProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'filteredProductsProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$filteredProductsHash();
@$internal
@override
$ProviderElement<List<Product>> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
List<Product> create(Ref ref) {
return filteredProducts(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(List<Product> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<List<Product>>(value),
);
}
}
String _$filteredProductsHash() => r'e4e0c549c454576fc599713a5237435a8dd4b277';

View File

@@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart'; import 'package:cached_network_image/cached_network_image.dart';
import '../../domain/entities/product.dart'; import '../../domain/entities/product.dart';
import '../pages/product_detail_page.dart';
import '../../../../shared/widgets/price_display.dart'; import '../../../../shared/widgets/price_display.dart';
/// Product card widget /// Product card widget
@@ -18,7 +19,13 @@ class ProductCard extends StatelessWidget {
clipBehavior: Clip.antiAlias, clipBehavior: Clip.antiAlias,
child: InkWell( child: InkWell(
onTap: () { onTap: () {
// TODO: Navigate to product details or add to cart // Navigate to product detail page
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductDetailPage(product: product),
),
);
}, },
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,

View File

@@ -0,0 +1,141 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../domain/entities/product.dart';
import '../pages/product_detail_page.dart';
import '../../../../shared/widgets/price_display.dart';
/// Product list item widget for list view
class ProductListItem extends StatelessWidget {
final Product product;
final VoidCallback? onTap;
const ProductListItem({
super.key,
required this.product,
this.onTap,
});
@override
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: InkWell(
onTap: onTap ??
() {
// Navigate to product detail page
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductDetailPage(product: product),
),
);
},
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
children: [
// Product Image
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: SizedBox(
width: 80,
height: 80,
child: product.imageUrl != null
? CachedNetworkImage(
imageUrl: product.imageUrl!,
fit: BoxFit.cover,
placeholder: (context, url) => const Center(
child: CircularProgressIndicator(),
),
errorWidget: (context, url, error) => Container(
color: Theme.of(context)
.colorScheme
.surfaceContainerHighest,
child: Icon(
Icons.image_not_supported,
color:
Theme.of(context).colorScheme.onSurfaceVariant,
),
),
)
: Container(
color: Theme.of(context)
.colorScheme
.surfaceContainerHighest,
child: Icon(
Icons.inventory_2_outlined,
color:
Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
),
const SizedBox(width: 16),
// Product Info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
product.name,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
if (product.description.isNotEmpty)
Text(
product.description,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 8),
Row(
children: [
PriceDisplay(price: product.price),
const Spacer(),
// Stock Badge
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
decoration: BoxDecoration(
color: _getStockColor(context, product.stockQuantity),
borderRadius: BorderRadius.circular(12),
),
child: Text(
'Stock: ${product.stockQuantity}',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.white,
fontWeight: FontWeight.w600,
),
),
),
],
),
],
),
),
],
),
),
),
);
}
Color _getStockColor(BuildContext context, int stock) {
if (stock == 0) {
return Colors.red;
} else if (stock < 5) {
return Colors.orange;
} else {
return Colors.green;
}
}
}

View File

@@ -2,6 +2,12 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_ce_flutter/hive_flutter.dart'; import 'package:hive_ce_flutter/hive_flutter.dart';
import 'app.dart'; import 'app.dart';
import 'core/constants/storage_constants.dart';
import 'features/products/data/models/product_model.dart';
import 'features/categories/data/models/category_model.dart';
import 'features/home/data/models/cart_item_model.dart';
import 'features/home/data/models/transaction_model.dart';
import 'features/settings/data/models/app_settings_model.dart';
/// Main entry point of the application /// Main entry point of the application
void main() async { void main() async {
@@ -12,18 +18,18 @@ void main() async {
await Hive.initFlutter(); await Hive.initFlutter();
// Register Hive adapters // Register Hive adapters
// TODO: Register adapters after running code generation Hive.registerAdapter(ProductModelAdapter());
// Hive.registerAdapter(ProductModelAdapter()); Hive.registerAdapter(CategoryModelAdapter());
// Hive.registerAdapter(CategoryModelAdapter()); Hive.registerAdapter(CartItemModelAdapter());
// Hive.registerAdapter(CartItemModelAdapter()); Hive.registerAdapter(TransactionModelAdapter());
// Hive.registerAdapter(AppSettingsModelAdapter()); Hive.registerAdapter(AppSettingsModelAdapter());
// Open Hive boxes // Open Hive boxes
// TODO: Open boxes after registering adapters await Hive.openBox<ProductModel>(StorageConstants.productsBox);
// await Hive.openBox<ProductModel>(StorageConstants.productsBox); await Hive.openBox<CategoryModel>(StorageConstants.categoriesBox);
// await Hive.openBox<CategoryModel>(StorageConstants.categoriesBox); await Hive.openBox<CartItemModel>(StorageConstants.cartBox);
// await Hive.openBox<CartItemModel>(StorageConstants.cartBox); await Hive.openBox<TransactionModel>(StorageConstants.transactionsBox);
// await Hive.openBox<AppSettingsModel>(StorageConstants.settingsBox); await Hive.openBox<AppSettingsModel>(StorageConstants.settingsBox);
// Run the app with Riverpod (no GetIt needed - using Riverpod for DI) // Run the app with Riverpod (no GetIt needed - using Riverpod for DI)
runApp( runApp(