So I have this product page where I would want to show recent visited product a.k.a product history. So I save this product id every time a user visits the page in the initState
, the problem is where am supposed to show the the history is in another page and it keeps showing one item(recent visited) instead of a list of them all(It replaces the previous one). Here’s my code
...
class _ProductInfoScreenState extends State<ProductInfoScreen> {
//initialise the list
List<String> visitedProduct = [];
Future setViewedProduct()async{
visitedProduct.add(widget.productId);
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList('viewedProductHistory', visitedProduct);
}
@override
void initState() {
getImage();
//Here
setViewedProduct();
super.initState();
}
}
....
///Getting the saved list
class _SearchTabState extends State<SearchTab> {
...
Future getVisitedProductsFuture()async{
SharedPreferences prefs = await SharedPreferences.getInstance();
var visitedProductsList = prefs.getStringList('viewedProductHistory');
return visitedProductsList;
}
...
SizedBox(
height: 200,
width: size.width,
child: FutureBuilder(
future: getVisitedProductsFuture(),
builder: (context, AsyncSnapshot recentVisitedProductsSnapshot) {
if(recentVisitedProductsSnapshot.hasData){
return SizedBox(
height: 130.0,
width:size.width,
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
children: List.generate(recentVisitedProductsSnapshot.data.length, (index) {
return Padding(
padding: const EdgeInsets.only(right: 14.0),
child: FutureBuilder(
future: ShopService().getSingleShopProduct(recentVisitedProductsSnapshot.data[index]),
builder: (context, AsyncSnapshot actualVisitedProductSnapshot) {
if(actualVisitedProductSnapshot.hasData){
print(recentVisitedProductsSnapshot.data.length);
return InkWell(
onTap: (){
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Stack(
children: [
Container(
height: 130.0,
width: 130.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
image: DecorationImage(
image: NetworkImage(actualVisitedProductSnapshot.data['product']['featured_image']['digital_ocean_url'].toString(),),
fit: BoxFit.contain
)
),
),
Positioned(
top: 5.0,
right: 5.0,
child: FutureBuilder(
future: ShopService().getWishlist(widget.user.id.toString()),
builder: (context, AsyncSnapshot wishlistSnapshot) {
var containsItem;
if(wishlistSnapshot.hasData){
containsItem = wishlistSnapshot.data.firstWhere((e)=> e['product_id'].toString() ==
actualVisitedProductSnapshot.data['product_id'].toString(), orElse:() => {});
if(containsItem['product_id'].toString() == actualVisitedProductSnapshot.data['product_id'].toString()){
return InkWell(
onTap: (){
ShopService().removeFromWishlist(
containsItem['id'].toString()
).then((value) {
if(value['error'] ){
setState(() {
});
Flushbar(
margin: const EdgeInsets.only( bottom: 12.0, left: 12.0, right: 12.0),
borderRadius: BorderRadius.circular(10.0),
message: 'Please try again later!!',
duration: const Duration(seconds: 2),
).show(context);
}
else{
setState(() {
});
Flushbar(
margin: const EdgeInsets.only( bottom: 12.0, left: 12.0, right: 12.0),
borderRadius: BorderRadius.circular(10.0),
message: 'Removed from wishlist!',
duration: const Duration(seconds: 2),
).show(context);
}
});
},
child: Container(
height: 35.0,
width: 35.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14.0),
color: AppColors.fontHeaderColor.withOpacity(0.2),
),
child: const Center(
child: Icon( Icons.favorite_rounded, color: Colors.redAccent,),
),
),
);
}else{
return InkWell(
onTap: (){
ShopService().addToWishlist(
actualVisitedProductSnapshot.data['merchant_id'].toString(),
widget.user.id.toString(),
actualVisitedProductSnapshot.data['product_id'].toString(),
actualVisitedProductSnapshot.data['id'].toString(),
).then((value) {
setState(() {
});
if(value['error'] && value['data'].isNotEmpty){
Flushbar(
margin: const EdgeInsets.only( bottom: 12.0, left: 12.0, right: 12.0),
borderRadius: BorderRadius.circular(10.0),
message: 'Item already exists',
duration: const Duration(seconds: 2),
).show(context);
} else if(value['error']){
Flushbar(
margin: const EdgeInsets.only( bottom: 12.0, left: 12.0, right: 12.0),
borderRadius: BorderRadius.circular(10.0),
message: 'Please try again later!!',
duration: const Duration(seconds: 2),
).show(context);
}
else{
setState(() {
});
Flushbar(
margin: const EdgeInsets.only( bottom: 12.0, left: 12.0, right: 12.0),
borderRadius: BorderRadius.circular(10.0),
message: 'Added to wishlist!',
duration: const Duration(seconds: 2),
).show(context);
}
});
},
child: Container(
height: 35.0,
width: 35.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14.0),
color: AppColors.fontHeaderColor.withOpacity(0.2),
),
child: const Center(
child: Icon(Icons.favorite_outline_rounded, color: AppTaste.whiteThemeColor,),
),
),
);
}
}else{
return Container(
height: 35.0,
width: 35.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14.0),
color: AppColors.fontHeaderColor.withOpacity(0.2),
),
child: const Center(
child: Icon(Icons.favorite_outline_rounded, color: AppTaste.whiteThemeColor,),
),
);
}
}
),
),
],
),
// const SizedBox(height: 8.0,),
// SizedBox(
// width: 130.0,
// child: SmallTextWidget(
// align: TextAlign.start,
// text: productCategorySnapshot.data[index]['company']['name'].toString(), color: AppTaste.font1ThemeColor, size: 12.0,),
// ),
const SizedBox(height: 8.0,),
Flexible(child: SizedBox(
width: 130.0,
child: SmallTextWidget(
align: TextAlign.start,
text: actualVisitedProductSnapshot.data['product']['title'].toString(), color: AppTaste.secondaryThemeColor, size: 14.0, fontWeight: FontWeight.w600,))),
const SizedBox(height: 8.0,),
SizedBox(
width: 130.0,
child: SmallTextWidget(
align: TextAlign.start, text: 'KES${double.parse(actualVisitedProductSnapshot.data['selling_price'].toString()).toStringAsFixed(0)}'.replaceAllMapped(reg ,mathFunc), color: AppTaste.secondaryThemeColor, size: 14.0,),
),
],
),
);
}else{
return SizedBox();
}
}
),
);
}),
),
);
}else{
return HorizontalShimmerWidget(context);
}
}
),
),
}
2
Answers
I see your problem instantly because I had the same problem, The problem is that you are not adding to the
List<String> visitedProduct = [];
so it is overriding each time, for example (my app):All that I am trying to show here is that you should add the code
Add recent viewed
to theList<String> visitedProduct = [];
list so that it can display a listThe deal is that method
setStringList(String key, List<String> value)
is NOT adding an item to your stored list but it’s completely replacing your stored list with newList<String> value
.To achieve what you want you need to:
Get your stored list from shared preferences or if it was not stored previously create a new one:
Add your recently visited product id to the saved list:
Save your list to the shared preferences: