Home > database >  Flutter Dart firstwhere returning only the first item in a list, which function can return all the i
Flutter Dart firstwhere returning only the first item in a list, which function can return all the i

Time:08-19

I am trying to return a list of all inputs once in an array of lists. I use the extension on function to get a list of "Instance of ProductQuantity". The result should look like this:

[Instance of 'ProductQuantity', Instance of 'ProductQuantity', Instance of 'Product Quantity']

I am currently getting only 1 instance: [Instance of 'ProductQuantity'] when there should be multiple instances.

Here is the function which i believe the problem is from the firstWhere :

extension on List<ProductQuantity> {
  void addProductQuantity({required int productID, required int quantity}) {
    if (isNotEmpty) {
      try {
        var productWid = firstWhere((p) => p.productId == productID);
        productWid.quantity == quantity;
      } catch (e) {
        add(ProductQuantity(productId: productID, quantity: quantity));
      }
    } else {
      add(ProductQuantity(productId: productID, quantity: quantity));
    }
  }
}

For adding the values i use the following a for Loop then add the above function to an empty list:

                              setState(() {
                                for (var i = 0; i < plist.length; i  ) {
                                  idInOrder = plist[i];

                                  // debugPrint(plist[i].toString());
                                }
                                for (var i = 0; i < qt.length; i  ) {
                                  quantityInOrder = qt[i];
                                  // debugPrint(qt[i].toString());
                                }
                              });
                              _orderProductQuantity.addProductQuantity(
                                  productID: idInOrder,
                                  quantity: quantityInOrder);

For the full code,

class CheckoutScreen extends StatefulWidget {
  const CheckoutScreen({Key? key}) : super(key: key);

  @override
  State<CheckoutScreen> createState() => _CheckoutScreenState();
}

class _CheckoutScreenState extends State<CheckoutScreen> {
  @override
  Widget build(BuildContext context) {
    final List<ProductQuantity>? productQuantity = [];
    var _orderProductQuantity = <ProductQuantity>[];
    var idInOrder;
    var quantityInOrder;

    final OrderDetails? orderDetails;

    return Scaffold(
        appBar: AppBar(
          backgroundColor: buttonBG,
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              height: 60,
              alignment: Alignment.bottomCenter,
              decoration: const BoxDecoration(color: buttonBG),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Center(
                    child: BlocBuilder<CartBloc, CartState>(
                      builder: (context, state) {
                        if (state is CartLoaded) {
                          return TextButton(
                            onPressed: () async {
                              var alc = state.cart
                                  .productQuantity(state.cart.products);
                              var qt = alc.values.toList(); // [1, 5]
                              var pio = alc.keys.toList();
                              var group = pio
                                  .groupListsBy((element) => element.id)
                                  .map((key, value) =>
                                      MapEntry(key, value.length));
                              var plist = group.keys.toList(); // [10, 11]
                              Map aos = state.cart
                                  .productQuantity(state.cart.products);

                              setState(() {
                                for (var i = 0; i < plist.length; i  ) {
                                  idInOrder = plist[i];

                                  // debugPrint(plist[i].toString()); // 10 11 (different lines)
                                }
                                for (var i = 0; i < qt.length; i  ) {
                                  quantityInOrder = qt[i];
                                  // debugPrint(qt[i].toString()); // 1 5 (different lines)
                                }
                              });
                              _orderProductQuantity.addProductQuantity(
                                  productID: idInOrder,
                                  quantity: quantityInOrder);
                              String productInstance =
                                  json.encode(_orderProductQuantity);
                              debugPrint('productQuantity:$productInstance}');
                            },
                            child: Text(
                              'Place Order',
                              style: Theme.of(context)
                                  .textTheme
                                  .button!
                                  .copyWith(color: Colors.white),
                            ),
                          );
                        }
                        return const Text('There was an error');
                      },
                    ),
                  ),
                  IconButton(
                    onPressed: () {},
                    icon: const Icon(
                      Icons.arrow_forward,
                      color: Colors.white,
                    ),
                  )
                ],
              ),
            ),
          ],
        ));
  }
}

extension on List<ProductQuantity> {
  void addProductQuantity({required int productID, required int quantity}) {
    if (isNotEmpty) {
      try {
        var productWid = firstWhere((p) => p.productId == productID);
        productWid.quantity == quantity;
      } catch (e) {
        add(ProductQuantity(productId: productID, quantity: quantity));
      }
    } else {
      add(ProductQuantity(productId: productID, quantity: quantity));
    }
  }
}

Please how do i achieve this: This is a method of cart implementation that i am trying to do and this result will be sent to the api using a POST request. So end result is similar to:

{
  "productQuantity": [
    {
      "product_id": 10,
      "quantity": 1
    },
    {
      "product_id": 11,
      "quantity": 2
    }
  ],
  "order_details": {
    "subtotal": 5415.00,
    "delivery_fee": 25.000,
    "total": 155.00
  }
}

CodePudding user response:

You should use the where method instead of firstWhere, here is the doc: https://api.flutter.dev/flutter/dart-core/Iterable/where.html

As named, firstWhere will return only the first item found.

CodePudding user response:

use where it return iterable, so you want to make it into list ( toList() )

List<int> data = [1,0,2,3,0];
List<int> resultOfFilter = data.where((element) => element == 0).toList();

you will get [0,0] as result

  • Related