I am very new to flutter and following a tutorial video on how to create a cart for a mobile application, this has a cart Screen with a widget inside it for calculating a cart total, this mentioned cart total widget relies on another file i named cart controller to calculate a subtotal for each item added to cart and a grand total for all cart items within the cart.
however when i build the app i keep getting an error stating Class 'String' has no instance method 'toStringAsFixed'
I need help on how i can be able to show the total of all items available in the cart
heres my code for the cart controller:
import 'package:get/get.dart';
import 'package:shop_app/models/things.dart';
class CartController extends GetxController{
//Add dictionary to store the products in the cart
var _things = {}.obs;
//void AddProduct
void addProduct(Things things) {
if (_things.containsKey(things)){
_things[things] += 1;
} else {_things[things] = 1;}
Get.snackbar("Product added!","You have added ${things.title} to the cart",
snackPosition: SnackPosition.TOP,
duration: Duration(seconds: 2),
);
}
//void RemoveProduct
void removeProduct(Things things){
if (_things.containsKey(things) && _things[things] == 1) {
_things.removeWhere((key, value) => key == things);
}
else {
_things[things] -= 1;
}
Get.snackbar("Product removed!","You have removed ${things.title} from the cart",
snackPosition: SnackPosition.BOTTOM,
duration: Duration(seconds: 2),
);
}
//get Products;
get products => _things;
//get ProductsSubtotal
get productsSubtotal => _things.entries
.map((things) => things.key.price * things.value)
.toList();
//get Total
get total => _things.entries
.map((things) => things.key.price * things.value)
.toList()
.reduce((value, element) => value + element)
.toStringAsFixed(2);
}
heres my code for the cart total widget that's supposed to display this grand total:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shop_app/controllers/cart_controller.dart';
class CartTotal extends StatelessWidget {
final CartController controller = Get.find();
CartTotal({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 50),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Total',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
Obx( () =>
Text(
//
'${controller.total}',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
],
),
);
}
}