paymentItemsFromRequest function

List<PaymentItem> paymentItemsFromRequest(
  1. PaymentRequest request
)

Builds a PaymentItem list for the pay package from PaymentRequest.orderDetails (single "Total" line with summed amount).

Ensures label and amount are never null/empty to avoid PlatformException(10) from Google Pay.

Implementation

List<PaymentItem> paymentItemsFromRequest(PaymentRequest request) {
  double total = 0;
  if (request.orderDetails.isNotEmpty) {
    for (final o in request.orderDetails) {
      final cleaned = o.amount.replaceAll(RegExp(r'[^\d.]'), '');
      total += double.tryParse(cleaned) ?? 0;
    }
  }
  // Ensure amount is always a valid non-empty string (avoids PlatformException 10)
  final amountStr = total > 0 ? total.toStringAsFixed(2) : '0.00';
  return [
    PaymentItem(
      label: 'Total',
      amount: amountStr,
      status: PaymentItemStatus.final_price,
      type: PaymentItemType.total,
    ),
  ];
}