skip to Main Content

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


  1. 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):

    List<String> joinedRides =  [];
    
    _getDBRides() {
        return Expanded(
          child: FirebaseAnimatedList(
         
              Map Rides = snapshot.value as Map;
              Rides['key'] = snapshot.key; // this is important because you want to use this string (unique key of each item in the database to add to the list)
    
            },
          ),
        );
      }
    
      Widget listItem({
        required Map Rides,
      }) {
        saveprefs() async {
          SharedPreferences prefs = await SharedPreferences.getInstance();
          await prefs.setStringList("joined_rides", joinedRides);
        }
    
        return Slidable(
                onPressed: (context) async {
                  print(Rides['key']);
                  if (!joinedRides.contains(Rides['key'])) {
    
    // as you can see i add to the joinedRides list this is very important
    
                    joinedRides.add(Rides['key']);
                    saveprefs();
    

    All that I am trying to show here is that you should add the code Add recent viewed to the List<String> visitedProduct = []; list so that it can display a list

    Login or Signup to reply.
  2. The 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 new List<String> value.

    To achieve what you want you need to:

    1. Get your stored list from shared preferences or if it was not stored previously create a new one:

      final savedInPrefsOrNewList = preferences.getStringList('your_key') ?? [];
      
    2. Add your recently visited product id to the saved list:

      savedInPrefsOrNewList.add(widget.productId);
      
    3. Save your list to the shared preferences:

      preferences.setStringList('your_key', savedInPrefsOrNewList);
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search