How to increase or decrease Quantity for each product Using Flutter - Sqflite - BloC - WooCommerce

Viewed 365

Hello I'm really need help with this issue,
How to increase or decrease Quantity for each product Using Flutter - Sqflite - BloC - WooCommerce
I want to add for each item each quantity to POST Order
i think must to add this to Product model but i don't know to handle this issue

this is the Product Model class

List<Product> productModelFromJson(String str) =>
    List<Product>.from(json.decode(str).map((x) => Product.fromJson(x)));

String productModelToJson(List<Product> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Product {
  Product({
    required this.id,
    required this.name,
    required this.parent,
    required this.type,
    required this.variation,
    required this.permalink,
    required this.sku,
    required this.shortDescription,
    required this.description,
    required this.onSale,
    required this.prices,
    required this.priceHtml,
    required this.averageRating,
    required this.reviewCount,
    required this.images,
    required this.categories,
    required this.tags,
    required this.attributes,
    required this.variations,
    required this.hasOptions,
    required this.isPurchasable,
    required this.isInStock,
    required this.isOnBackorder,
    required this.lowStockRemaining,
    required this.soldIndividually,
    required this.quantityLimit,
    required this.addToCart,
   // required this.quantity,
    //required this.counter,
  });

  int? id;
  String? name;
  int? parent;
  Type? type;
  String? variation;
  String? permalink;
  String? sku;
  String? shortDescription;
  String? description;
  bool? onSale;
  Prices? prices;
  String? priceHtml;
  String? averageRating;
  int? reviewCount;
  List<Image2>? images;
  List<Category2>? categories;
  List<dynamic>? tags;
  List<dynamic>? attributes;
  List<dynamic>? variations;
  bool? hasOptions;
  bool? isPurchasable;
  bool? isInStock;
  bool? isOnBackorder;
  dynamic? lowStockRemaining;
  bool? soldIndividually;
  int? quantityLimit;
  AddToCart? addToCart;
  //  int quantity = 1;
 // Quantity counter=1;

  factory Product.fromJson(Map<String, dynamic> json) => Product(
        id: json["id"],
        name: json["name"],
        parent: json["parent"],
        type: typeValues.map[json["type"]],
        variation: json["variation"],
        permalink: json["permalink"],
        sku: json["sku"],
        shortDescription: json["short_description"],
        description: json["description"],
        onSale: json["on_sale"],
        prices: Prices.fromJson(json["prices"]),
        priceHtml: json["price_html"],
        averageRating: json["average_rating"],
        reviewCount: json["review_count"],
        images: List<Image2>.from(json["images"].map((x) => Image2.fromJson(x)))
            .toList(),
        categories: List<Category2>.from(
            json["categories"].map((x) => Category2.fromJson(x))),
        tags: List<dynamic>.from(json["tags"].map((x) => x)),
        attributes: List<dynamic>.from(json["attributes"].map((x) => x)),
        variations: List<dynamic>.from(json["variations"].map((x) => x)),
        hasOptions: json["has_options"],
        isPurchasable: json["is_purchasable"],
        isInStock: json["is_in_stock"],
        isOnBackorder: json["is_on_backorder"],
        lowStockRemaining: json["low_stock_remaining"],
        soldIndividually: json["sold_individually"],
        quantityLimit: json["quantity_limit"],
        addToCart: AddToCart.fromJson(json["add_to_cart"]),
      //  quantity: 1,
       // counter: Quantity(counter: 1),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "parent": parent,
        "type": typeValues.reverse![type],
        "variation": variation,
        "permalink": permalink,
        "sku": sku,
        "short_description": shortDescription,
        "description": description,
        "on_sale": onSale,
        "prices": prices!.toJson(),
        "price_html": priceHtml,
        "average_rating": averageRating,
        "review_count": reviewCount,
        "images": List<dynamic>.from(images!.map((x) => x.toJson())),
        "categories": List<dynamic>.from(categories!.map((x) => x.toJson())),
        "tags": List<dynamic>.from(tags!.map((x) => x)),
        "attributes": List<dynamic>.from(attributes!.map((x) => x)),
        "variations": List<dynamic>.from(variations!.map((x) => x)),
        "has_options": hasOptions,
        "is_purchasable": isPurchasable,
        "is_in_stock": isInStock,
        "is_on_backorder": isOnBackorder,
        "low_stock_remaining": lowStockRemaining,
        "sold_individually": soldIndividually,
        "quantity_limit": quantityLimit,
        "add_to_cart": addToCart!.toJson(),
      };
}

class Quantity {
  int counter = 1;
  Quantity({required this.counter});

  void increaseCounter(){
    counter++;
  }
  void decreaseCounter(){
   if(counter>1)
     counter--;
  }
}

class AddToCart {
  AddToCart({
    required this.text,
    required this.description,
    required this.url,
  });

  Text2? text;
  String? description;
  String? url;

  factory AddToCart.fromJson(Map<String, dynamic> json) => AddToCart(
        text: textValues.map[json["text"]],
        description: json["description"],
        url: json["url"],
      );

  Map<String, dynamic> toJson() => {
        "text": textValues.reverse![text],
        "description": description,
        "url": url,
      };
}

enum Text2 { EMPTY }

final textValues = EnumValues({"إضافة إلى السلة": Text2.EMPTY});

class Category2 {
  Category2({
    required this.id,
    required this.name,
    required this.slug,
    required this.link,
  });

  int? id;
  Name? name;
  String? slug;
  String? link;

  factory Category2.fromJson(Map<String, dynamic> json) => Category2(
        id: json["id"],
        name: nameValues.map[json["name"]],
        slug: json["slug"],
        link: json["link"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": nameValues.reverse![name],
        "slug": slug,
        "link": link,
      };
}

enum Name { EMPTY, NAME, PURPLE }

final nameValues = EnumValues({
  "انظمة امنية ومراقبة": Name.EMPTY,
  "اكسسوار رجالي": Name.NAME,
  "اكسسوار نسائي": Name.PURPLE
});

class Image2 {
  Image2({
    required this.id,
    required this.src,
    required this.thumbnail,
    required this.srcset,
    required this.sizes,
    required this.name,
    required this.alt,
  });

  int? id;
  String? src;
  String? thumbnail;
  String? srcset;
  Sizes? sizes;
  String? name;
  String? alt;

  factory Image2.fromJson(Map<String, dynamic> json) => Image2(
        id: json["id"],
        src: json["src"],
        thumbnail: json["thumbnail"],
        srcset: json["srcset"],
        sizes: sizesValues.map[json["sizes"]],
        name: json["name"],
        alt: json["alt"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "src": src,
        "thumbnail": thumbnail,
        "srcset": srcset,
        "sizes": sizesValues.reverse![sizes],
        "name": name,
        "alt": alt,
      };
}

enum Sizes { MAX_WIDTH_500_PX_100_VW_500_PX }

final sizesValues = EnumValues(
    {"(max-width: 500px) 100vw, 500px": Sizes.MAX_WIDTH_500_PX_100_VW_500_PX});

class Prices {
  Prices({
    required this.currencyCode,
    required this.currencySymbol,
    required this.currencyMinorUnit,
    required this.currencyDecimalSeparator,
    required this.currencyThousandSeparator,
    required this.currencyPrefix,
    required this.currencySuffix,
    required this.price,
    required this.regularPrice,
    required this.salePrice,
    required this.priceRange,
  });

  Currency? currencyCode;
  Currency? currencySymbol;
  int? currencyMinorUnit;
  CurrencyDecimalSeparator? currencyDecimalSeparator;
  CurrencyThousandSeparator? currencyThousandSeparator;
  CurrencyPrefix? currencyPrefix;
  String? currencySuffix;
  String? price;
  String? regularPrice;
  String? salePrice;
  dynamic? priceRange;

  factory Prices.fromJson(Map<String, dynamic> json) => Prices(
        currencyCode: currencyValues.map[json["currency_code"]],
        currencySymbol: currencyValues.map[json["currency_symbol"]],
        currencyMinorUnit: json["currency_minor_unit"],
        currencyDecimalSeparator: currencyDecimalSeparatorValues
            .map[json["currency_decimal_separator"]],
        currencyThousandSeparator: currencyThousandSeparatorValues
            .map[json["currency_thousand_separator"]],
        currencyPrefix: currencyPrefixValues.map[json["currency_prefix"]],
        currencySuffix: json["currency_suffix"],
        price: json["price"],
        regularPrice: json["regular_price"],
        salePrice: json["sale_price"],
        priceRange: json["price_range"],
      );

  Map<String, dynamic> toJson() => {
        "currency_code": currencyValues.reverse![currencyCode],
        "currency_symbol": currencyValues.reverse![currencySymbol],
        "currency_minor_unit": currencyMinorUnit,
        "currency_decimal_separator":
            currencyDecimalSeparatorValues.reverse![currencyDecimalSeparator],
        "currency_thousand_separator":
            currencyThousandSeparatorValues.reverse![currencyThousandSeparator],
        "currency_prefix": currencyPrefixValues.reverse![currencyPrefix],
        "currency_suffix": currencySuffix,
        "price": price,
        "regular_price": regularPrice,
        "sale_price": salePrice,
        "price_range": priceRange,
      };
}

enum Currency { EGP }

final currencyValues = EnumValues({"EGP": Currency.EGP});

enum CurrencyDecimalSeparator { EMPTY }

final currencyDecimalSeparatorValues =
    EnumValues({".": CurrencyDecimalSeparator.EMPTY});

enum CurrencyPrefix { EGP }

final currencyPrefixValues = EnumValues({"EGP ": CurrencyPrefix.EGP});

enum CurrencyThousandSeparator { EMPTY }

final currencyThousandSeparatorValues =
    EnumValues({",": CurrencyThousandSeparator.EMPTY});

enum Type { SIMPLE }

final typeValues = EnumValues({"simple": Type.SIMPLE});

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String>? reverseMap;

  EnumValues(this.map);

  Map<T, String>? get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}

this is Order Item Widget

Widget showOrderItem(
  Map model,
  index,
  context,
{ Product? product}
) {
  dynamic convertPrice(int length) {
    if (model['saleprice'].length == length) {
      String price = model['saleprice'];
      String stringPrice = price.substring(0, length - 2);
      int parsePrice = int.parse(stringPrice);
      return parsePrice;
    }
  }
 
  double cardWidth = MediaQuery.of(context).size.width / 1.8;
  return Dismissible(
    key: UniqueKey(),
    onDismissed: (direction) {
      FavoritesCubit.get(context)
          .deleteItemOrderListFromDatabase(id: model['id']);
    },
    child: Column(
      children: [
        GestureDetector(
          onTap: () {
            /*Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => ProductDetailsScreen(product: product!),
                ));*/
          },
          child: Card(
            margin: EdgeInsets.all(15),
            child: Container(
              width: double.infinity,
              height: 200,
              child: Stack(
                children: [
                  Row(
                    textDirection: TextDirection.rtl,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      /// RightSide
                      Column(
                        textDirection: TextDirection.rtl,
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          /// image
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Container(
                              height: 80,
                              width: 100,
                              child: CachedNetworkImage(
                                imageUrl: '${model['image']}',
                                // height: height / 1.7,
                                height: 120,
                                width: cardWidth / 1.4,
                                fit: BoxFit.contain,
                              ),
                            ),
                          ),
                          Spacer(),
                          Column(
                            children: [
                              Text('الكمية'),
                              SizedBox(
                                height: 5,
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  TextButton(
                                    onPressed: () {
                                     //  FavoritesCubit.get(context)
                                     //      .increaseQuantity(index);
                                    // model['quantity'][index]++;
                                      FavoritesCubit.get(context).increaseQuantity();
                                    // quantity++;
                                    },
                                    style: ButtonStyle(),
                                    child: Text(
                                      '+',
                                      style: TextStyle(
                                        color: Colors.black,
                                        fontSize: 20,
                                      ),
                                    ),
                                  ),
                                  //SizedBox(width: 20,),
                                  Text(
                                    '$quantity',
                                   // '${model['quantity']}'
                                  // '${FavoritesCubit.get(context).quantity}',
                                    //'${model['quantity']}',
                                  ),
                                  // SizedBox(width: 10,),
                                  TextButton(
                                    onPressed: () {
                                      // FavoritesCubit.get(context).decreaseQuantity();
                                      // var quantity =  product.quantity;
                                      // quantity--;
                                    },
                                    child: Text(
                                      '-',
                                      style: TextStyle(
                                        color: Colors.black,
                                        fontSize: 20,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                      Container(
                        width: 1,
                        color: Colors.black12,
                      ),

                      /// Center
                      Expanded(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Expanded(
                              child: Directionality(
                                textDirection: TextDirection.rtl,
                                child: ListTile(
                                  title: Text(
                                    '${model['title']}',
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 4,
                                  ),
                                      isThreeLine: false,
                                ),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Container(
                                width: double.infinity,
                                padding:
                                    const EdgeInsets.only(left: 10, right: 10),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.only(
                                    bottomLeft: Radius.circular(10),
                                    bottomRight: Radius.circular(10),
                                  ),
                                  color: Colors.blueAccent,
                                ),
                                child: Center(
                                  child: RichText(
                                    maxLines: 2,
                                    text: TextSpan(
                                      children: [
                                        if (model['saleprice'].length == 4)
                                          TextSpan(
                                              text:
                                                  //'${intPrice}',
                                                  '${convertPrice(4)! * FavoritesCubit.get(context).quantity}'
                                              //'${model['saleprice'].substring(0, 2)*FavoritesCubit.get(context).quantity}',
                                              //'$productprice',
                                              // style: sPriceSmall,
                                              ),
                                        if (model['saleprice'].length == 5)
                                          TextSpan(
                                              text:
                                                  //  '${intPrice}',
                                                  '${convertPrice(5)! * FavoritesCubit.get(context).quantity}'
                                              //'${model['saleprice'].substring(0, 3)*FavoritesCubit.get(context).quantity}',
                                              //'$productprice',
                                              // style: sPriceSmall,
                                          ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                              ],
                            ),
                          ),
                        ],
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    ),
  );
}

This is Cubit

import 'package:bloc/bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:khsomat/business_logic/favorites_cubit/favorites_states.dart';
import 'package:khsomat/data/models/products_model.dart';
import 'package:sqflite/sqflite.dart';

class FavoritesCubit extends Cubit<FavoritesStates> {
  FavoritesCubit() : super(FavoritesInitialState());

  static FavoritesCubit get(context) => BlocProvider.of(context);

  late Database database;

  List<Map<dynamic, dynamic>> wishList = [];
  List<Map<dynamic, dynamic>> orderList = [];

  Future<void> createDatabase() async {
  database = await openDatabase(
      'wishlist.db',
      version: 1,
      onCreate: (database, version) {
        print('database Created Successfully !');
        database
            .execute(
                'CREATE TABLE wishlist (id INTEGER PRIMARY KEY, title TEXT, image TEXT, regularprice TEXT,saleprice TEXT,permalink TEXT)');
        database
            .execute(
            'CREATE TABLE orderlist (id INTEGER PRIMARY KEY, title TEXT, image TEXT, regularprice TEXT,saleprice TEXT,permalink TEXT,quantity INTEGER)');

        print('table Created Successfully !');
        //     .catchError((error) {
        //   print('Error While Creating Table Wishlist : ${error.toString()}');
        // });
      },
      onOpen: (database) {
        getWishListDataFromDatabase(database);
        getOrderListDataFromDatabase(database);
        // print(productList);
        print('database Opened Successfully !');
      },
    );
     // database = value;
      print(wishList);

      emit(AppCreatedDatabaseState());

  }

  Future insertToDatabase({
    required int id,
    required String text,
    required String image,
    required String regularprice,
    required String saleprice,
    required String permalink,

  }) async {
    await database.transaction((txn) async {
      return await txn
          .rawInsert(
              'INSERT INTO wishlist(title,image,regularprice,saleprice,permalink) VALUES("$text","$image","$regularprice","$saleprice","$permalink")')
          .then((value) {
        print('$value inserted successfully');
        getWishListDataFromDatabase(database);
        print(wishList);
        emit(AppInsertedToDatabaseState());
      }).catchError((error) {
        print('Error When Inserting New Record ${error.toString()}');
      });
    });
  }

  Future insertToOrderListDatabase({
    required int id,
    required String text,
    required String image,
    required String regularprice,
    required String saleprice,
    required String permalink,
    required int quantity,
  }) async {
    await database.transaction((txn) async {
      return await txn
          .rawInsert(
          'INSERT INTO orderlist(title,image,regularprice,saleprice,permalink,quantity) VALUES("$text","$image","$regularprice","$saleprice","$permalink","$quantity")')
          .then((value) {
        print('$value inserted successfully');
        getWishListDataFromDatabase(database);
        print(orderList);
        emit(AppInsertedToDatabaseState());
      }).catchError((error) {
        print('Error When Inserting New Record ${error.toString()}');
      });
    });
  }

  void getWishListDataFromDatabase(database) async {
    //productList = [];
    emit(AppGetWishListDatabaseLoadingState());

    await database.rawQuery('SELECT * FROM wishlist').then((value) {
      value.forEach((product) {
        wishList.add(product);
        print(wishList);
      });
      emit(GetWishListFromDataBaseState());
    });
  }

  void getOrderListDataFromDatabase(database) async {
    //productList = [];
    emit(AppGetOrderListDatabaseLoadingState());

    await database.rawQuery('SELECT * FROM orderlist').then((value) {
      value.forEach((product) {
        orderList.add(product);
        print(orderList);
      });
      emit(GetOrderListFromDataBaseState());
    });
  }

  void deleteItemWishListFromDatabase({
    required int id,
  }) async {

    await database
        .rawDelete('DELETE FROM wishlist WHERE id = ?', [id]).then((value) {
    //  getWishListDataFromDatabase(database);
      emit(DeleteWishListDataFromDatabaseState());
    });
  }


  void deleteItemOrderListFromDatabase({
    required int id,
  }) async {

    await database
        .rawDelete('DELETE FROM orderlist WHERE id = ?', [id]).then((value) {
      getWishListDataFromDatabase(database);
      emit(DeleteOrderListDataFromDatabaseState());
    });
  }

   Product? product;
  //
  // int quantity = product!.quantityLimit!;
  //var quantity2= database.rawQuery('SELECT quantity from orderlist');

int quantity=1;


  void increaseQuantity(){

   quantity++;
    emit(IncreaseQuantityState());
  }
  void decreaseQuantity(){
    if(quantity > 1)
      {
        quantity--;
      }
    emit(DecreaseQuantityState());
  }

}
0 Answers
Related