Flutter Dart: Dynamic Relationship inside Model Class Field - flutter

I've used Laravel, where we can define relationships inside the model itself. So is that possible in Dart/Flutter?
I've built this Cart Model where Grand-total should be dynamic.
So whenever I create an instance of this Cart Model, grand total will be auto-calculated once we enter the total & discount. until then the default value 0.
code from the image above:
class Cart {
Cart({
this.total = 0,
this.discount = 0,
this.grandTotal, // I want this field dynamic: (grandtotal = total - discount)
});
int total;
int discount;
int? grandTotal;
}

define a getter method to calculate grandTotal.
Sample code:
int? get grandTotal {
// TODO: check for null cases here
return total - discount;
}

Related

How to pass values to another screen with flutter bloc

how to know pass values for calculation Bmi of User like (height of user gender and age and weight) but with BLoC I want to know passing this information from BmiModule
to ResultModule
Note: I use Cubit to pass for BmiModule, but I can't pass value like isMale to ResultModule.
This is my code
class BmiCubit extends Cubit<BmiStates> {
BmiCubit() : super(BmiInitialState());
// this value to use in selecting what is the gender of the user
bool isMale = false;
// value of height
int heightValue = 175;
// value of weight
int weightValue = 70;
// value of age
int ageValue = 20;
// It use to view variables like isMale in BmiModule but I can use it //to pass
// I try to passing but do not work
static BmiCubit get(BuildContext context) => BlocProvider.of(context);
}
I want to pass data to make some processing Bmi of user.
And thanks

How to make model fields observable in Flutter

I have a model called category , which has two fields, User has a list of categories and what to update the category name, for State Management getx is used
class Category {
String? categoryName;
bool status;
Category(this.categoryName,this.status);
}
I have a observable list called catList which is used in List widget
var catList = <Category>[].obs;
when I update the category field it doest not update
catList[index].categoryName = categoryChangedName.value;
but If I update the item in object and then assign the object to catList then It changed
catList[index] = Category(categoryChangedName.value, catList[index].status );
My question is how to make model fields observable, if we have more fields changes then this is not proper way.
As of GetX documentation you need to update values using method and call update(); method inside custom object !
Ex:
class Controller extends GetxController {
int counter = 0;
void increment() {
counter++;
update(); // look here!
}
}
Your use case might be like....
class Category {
String? categoryName;
bool status;
Category(this.categoryName,this.status);
void updateCategoryName(name){
this.categoryName = name;
update();
}
}
//Use like..
catList[index].updateCaetgoryName = categoryChangedName.value;

Getting and setting class attributes in Dart / Flutter

I would like to list a class's attributes and set them too. For example in a ListView when I tap on the value of an attribute I would like to increment it by 1.
Sample class:
class Person {
int age;
int height;
int weight;
Person({
this.age,
this.height,
this.weight,
});
}
Is it possible to list and set these values without writing getter and setter functions for each of the attributes?
In you code sample, you defined age, height, and weight as public. So, you don't need to define getters and setters. You can directly increment and decrement their values.
void main() {
final a = Person(age: 25, height: 210, weight: 90);
a.age++;
a.height++;
a.weight++;
print(a);
// This person is 26 years old, 211cm tall and weights 91kg
}
class Person {
int age;
int height;
int weight;
Person({
this.age = 0,
this.height = 0,
this.weight = 0,
});
toString() => 'This person is $age years old, ${height}cm tall and weights ${weight}kg';
}
However, you might encounter problems by mutating objects if later, you rely on state equality to rebuild a Widget. It's better to handle your State objects as being immutable.
Then, regarding listing the values, if you refer to [dart:mirrors][1], it's not supported by Flutter.

How to observe ObservableList item properties changes

I'm building a shopping app in Flutter using MVC pattern and mobx for app state management.
At the moment, I have a mobx store for cart items and one store for the cart controller.
The cart controller has a ObservableList of cart items and problem is that I don't know if there's a way of observing changes on cart items.
For instance, I'd like to observe cartItem.title or cartItem.total.
Is there a way to track this with ObservableList?
And whats is .observe() method the observable list has? (Think the documentation wasn't clear for me)
UPDATE: SAMPLE CODE
As I said I have to mobx sotres, one for the cart item and for the cart itself.
In the cart item store:
import 'package:mobx/mobx.dart';
part 'cart-item.model.g.dart';
class CartItemModel = _CartItemModel with _$CartItemModel;
abstract class _CartItemModel with Store {
int id;
String title;
String price;
String description;
#observable
int _quantity = 0;
#observable
double _total = 0;
_CartItemModel({
this.id,
this.title,
this.price,
this.description,
}) {
reaction(
(_) => _quantity,
(quantity) {
getTotal();
},
);
}
getItemQuantity() => _quantity.toString(); // Return item quantity
#action
increase() {
// Increase item quantity
if (_quantity <= 99) {
_quantity++;
}
}
#action
decrease() {
// Decrease item quantity
if (_quantity > 0) {
_quantity--;
}
}
#action
getTotal() {
// Return total price by item quantity
_total = double.parse(price) * _quantity;
return _total.toString();
}
}
And then in the cart controller:
import 'package:faccioo_user_app/models/cart-item.model.dart';
import 'package:mobx/mobx.dart';
part 'cart.controller.g.dart';
class CartController = _CartController with _$CartController;
abstract class _CartController with Store {
#observable
ObservableList<CartItemModel> cartItems = ObservableList<CartItemModel>();
#action
addItem(CartItemModel item) {
cartItems.insert(0, (item));
item.increase();
}
#action
removeItem(CartItemModel item) {
cartItems.removeWhere((cartItem) => cartItem.id == item.id);
getTotal();
}
#action
getSubtotal() {
cartItems.forEach((item) {
subtotal = subtotal + double.parse(item.getTotal());
});
return subtotal.toString();
}
#action
getTotal() {
total = (subtotal + shippingFee + serviceFee + change) - discount;
return total.toString();
}
}
The view is not being notified by the changes in cartItem.total, for example?. How do I observe changes in cartItemModel.total from ObservableLis?
To be more clear I got this print in which we can see that cart item quantity and total increase, therefore CartItemModel reactivity is working fine, but the cart controller can't track those changes from ObservableList, then the controller is not updating the view.
I'd really appreciate links and references from where I can learn more about mobx with Flutter and observable lists.
Cart view with cart item
this is an old question but I will share the hints for the solution and how to improve it.
You don't need to create a store for the model, just wrap the properties with #observable, #computed, etc.
Actions are meant to write to the store and update the store properties. If you want to read properties, just write a simple get property without the #action annotation, or if you want to read a property based on other #observable properties, use the get with #computed.
The store should be only the CartController in which you should have a #computed property that will change based on other properties changes, e.g. for the CartController store:
The CartItemModel should be transformed into a simple data class with getters and setters and is the store that will manage its state.
I didn't check in terms of types .. etc.., the getters are missing the return types, only the setters that don't need return type.
#computed
double get total() => subtotal + shippingFee + serviceFee + change - discount;
#computed
double get subtotal() {
double subTotalAggregator = 0;
cartItems.forEach((item) {
subTotalAggregator += double.parse(item.getTotal());
});
return subTotalAggregator;
}

How to count the sum of amount in list by group?

Im trying to create a listview where group by label. like this
VIEW IMAGE
and i want to get the total amount by group
how to achieve that ?
i use GroupListView in flutter to group my list
my model in list
`class ExpensesModel {
final int id;
final String label;
final int amount;
final int icon;
`
I found this code to get the length per list but im confuse how to get the amount.
`Widget countTitle(String title){
totalAmount = expensesContainer.where((ec) => ec.label == title).toList().length.toString();
return Text(totalAmount);
}`
you can use List.map() to iterate to all the elements of the list.Then you can check the lebel.If it matches then you can add its amount to the total.
Widget countTitle(String title){
int totalAmount=0;
expensesContainer.map((ec){
if(ec.lebel==title)
totalAmount+=ec.amount;
}
return Text(totalAmount.toString());
}`