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 .
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:
setStringList("cartProducts", Data);
- cartProducts is name for to saved data use the same to get data.Data
is your List<Map<String, dynamic>> variable.listItems
- use this as a variable to set the data- Call
getCartProducts()
ininitState()
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.