Home > Mobile >  How to add product to cart in flutter?
How to add product to cart in flutter?

Time:07-08

I have the list of map of product and i want to add that product to cart page on ontap .

I have the list of map of product and i want to add that product to cart page on ontap .

This is my map of product

This is my favourite button

I want to add those products in cart page when user tap the favourite button..... enter image description here

CodePudding user response:

Use flutter shared_preferences package. Call SharedPreferences as async function, to save the data use setStringList()

saveCartProducts() async{
 SharedPreferences prefs = await SharedPreferences.getInstance();
 prefs.setStringList("cartProducts", Data);
}

To get save data user getStringList() function

getCartProducts() async {
 SharedPreferences prefs = await SharedPreferences.getInstance();
 var cartProducts= prefs.getStringList("cartProducts");
 setState(() {
  listItems = cartProducts;
 });
}

Notes:

  1. setStringList("cartProducts", Data); - cartProducts is name for to saved data use the same to get data. Data is your List<Map<String, dynamic>> variable.
  2. listItems - use this as a variable to set the data
  3. Call getCartProducts() in initState()

CodePudding user response:

You need to make the data an object, store the data, and then send the data to the Cart Page.

data.dart

class Data{
  List<Map<String, dynamic>> data = [
    {
     'img': 'Image1',
     'price': '\$ 120',
     'name':  'Headphone',
     'str': 'str1',
     'category': 'Electronics',
    },
    {
      'img': 'Image2',
      'price': '\$ 150',
      'name':  'Gaming Controller',
      'str': 'str1',
      'category': 'Electronics',
    }
  ];
}

After creating a data object in main, when you click the shopping cart icon, the data is saved in a random list.

///create Object
Data data = Data();

List<Map<String, dynamic>> cart = [];

ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: items.length,
          itemBuilder: (context, index){
            if(items.isEmpty){
             return Text('no have items');
            }
            ......
            GestureDetector(
                onTap: (){
                   cart.add(data.data[index]);
                 },
              ),
          },
        ),

Finally, we send the data to the CartPage.

 Navigator.of(context).push(MaterialPageRoute(builder: (context) => CartPage(cartData: cart),))

Alternatively, you can use the Provider package for more convenient management.

  • Related