Marc
01/31/2023, 7:23 PMdata class Product(
val barcode: String,
val name: String,
val price: Double,
val category: String,
val image: Image?
)
class Cart : ViewModel() {
private val _cart: MutableStateFlow<List<Product>> = MutableStateFlow(listOf())
val cart: StateFlow<List<Product>> = _cart.asStateFlow()
init {
val product = Product("123456789", "Test", 13.99, "Test", null) // test product
_cart.update { it + product }
}
fun addProduct(product: Product) {
_cart.update { currentState ->
currentState + product
}
}
}
My composable:
@Composable
fun CartList(padding: PaddingValues) {
val cart: Cart = viewModel();
LazyColumn(contentPadding = padding) {
items(cart.cart.value) { product ->
CartItem(product)
}
}
}
QR-Code-Scanner which is called from a floating button:
@Composable
fun FloatButtonScanCode() {
// Local context
val context = LocalContext.current
val cart: Cart = viewModel()
FloatingActionButton(onClick = {
val optionsBuilder = GmsBarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_EAN_13, Barcode.FORMAT_EAN_8
)
val options = optionsBuilder.build()
val gmsBarcodeScanner = GmsBarcodeScanning.getClient(context, optionsBuilder.build())
gmsBarcodeScanner
.startScan()
.addOnSuccessListener { barcode: Barcode ->
if (barcode.rawValue != null) {
cart.addProduct(Product("123456789", "Test2", 1.99, "Test", null)) // <-- this is where I add a new product to the cart, but after calling addProduct the element with the item list does not re-render
println("Added product: Test2 to cart")
println("Cart ${cart.cart.value}") // proof that the new product is added to the cart-array
}
}
.addOnFailureListener { e: Exception -> System.err.println(e) }
.addOnCanceledListener {
System.err.println("Cancelled")
}
}) {
Icon(Icons.Outlined.AddCircle, contentDescription = "Add")
}
}
Ian G. Clifton
01/31/2023, 7:36 PMMarc
02/01/2023, 9:27 PMIan G. Clifton
02/02/2023, 1:02 AM