I'm new to flutter but I'm trying to learn it the right way (Clean Structure) so that I can reuse my code later, although I'm a Programmer for 7 years and I know the concepts.
the App is using these packages (GetX & ObjectBox), the issue is that I can't make them work together in my below app structure:
lib
app
├───database
│ ├───helpers
│ └───models
├───features
│ ├───dashboard
│ │ ├───bindings
│ │ ├───controllers
│ │ └───views
│ │ ├───components
│ │ └───screens
│ ├───products
│ │ ├───bindings
│ │ ├───controllers
│ │ └───views
│ │ ├───components
│ │ └───screens
│ ├───other features ...
the workflow for Products would be simply:
- create
Product
class model underapp/database/models/product.dart
- create
ObjectBox
class to manage Store underapp/database/helpers/objectbox.dart
- create
ProductHelper
class underapp/database/helpers/product.dart
with other Entities classes to handle CRUD operation for each Entity - create
ProductController
to interact betweenProductHelper
andProductScreen
underapp/features/products/
and Bindings ofcourse - finally pass data from controller to screen by GetX controller
Files below
Product model class:
part of app_models;
const String productTable = 'product';
class ProductFields {
static const String pk = 'pk';
static const String name = 'name';
static const String createdAt = 'create_at';
static const String updatedAt = 'updated_at';
}
@Entity()
class Product {
@Id()
int pk;
final String name;
final DateTime createdAt;
final DateTime? updatedAt;
Product({
this.pk = 0,
required this.name,
required this.createdAt,
this.updatedAt,
});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
pk: json['pk'] as int,
name: json['name'] as String,
createdAt: DateTime.parse(json['created_at'] as String),
updatedAt: DateTime.parse(json['updated_at'] as String),
);
}
Map<String, dynamic> toJson() => {
'pk': pk,
'name': name,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt?.toIso8601String(),
};
}
ObjectBox class:
class ObjectBox {
late final Store _store;
late final Box<Product> _boxProducts;
ObjectBox(this._store) {
_boxProducts = Box<Product>(_store);
}
static Future<ObjectBox> init() async {
final store = await openStore();
return ObjectBox(store);
}
}
ProductHelper class:
class ProductHelper extends ObjectBox {
ProductHelper(super.store) ;
Product? getProduct(int pk) => _boxProduct.get(pk);
Stream<List<Product>> getProducts() => _boxProduct
.query()
.watch(triggerImmediately: true)
.map((query) => query.find());
int insertProduct(Product branch) => _boxProduct.put(branch);
bool deleteProduct(int pk) => _boxProduct.remove(pk);
}
stuck at this level so far in controller can't use methods i.e. insertProduct()
from ProductHelper
class.
Advice from experts for the work flow and Structure of app files and clean code will be highly appreciated and useful for me and others.