我可以存储列表吗?共同偏好 [英] Can i store a List<dynamic> with shared preference

查看:74
本文介绍了我可以存储列表吗?共同偏好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在本地存储API的值列表。共享首选项是否允许存储列表,因为每次我尝试以共享首选项保存值时,我都会得到类型'列表'不是类型'列表'的子类型

I will like to store a list of values from an API locally. Does shared preference allow storing List because each time i try to save my values in shared preference, i get " type 'List' is not a subtype of type 'List'"

Future fetchAllProduct() async{
     try{
        for(int j = 1; j < 3; j++){
      final response = await 
  http.get('https://website/api/?page=1', 
     );
    List result = json.decode(response.body);
    products.addAll(result);

    //Saving fetched product list
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setStringList('prds', products);

    //final prds = preferences.getStringList('prd');
    }
  }catch (ex){
    print('$ex');
  }
  print(products);

}

我希望看到像这样的列表
[{产品ID:155,名称:Multi-vit,描述:Multi-vit,CostPrice:0.0,SalePrice:80,EatOutPrice:80,CategoryID:976,Barcode :, TaxRateID:null,}]

I'am expecting to see a list like this [{ProductID: 155, Name: Multi-vit, Description: Multi-vit, CostPrice: 0.0, SalePrice: 80, EatOutPrice: 80, CategoryID: 976, Barcode: , TaxRateID: null, }]

推荐答案

根据shared_preference的回购,应该可以存储列表。他们的测试用例与您的语法略有不同:
preferences.setStringList('List',kTestValues2 ['flutter.List'])方法。

According to shared_preference's repo it should be possible to store a List. Their test case have a slightly different syntax than yours: preferences.setStringList('List', kTestValues2['flutter.List']) which is different from your approach.

我假设您已将产品定义为列表。

I assume you have defined products as a List.

编辑:
为什么要在列表中存储列表?如果将结果设为字符串会怎样?

Why are you storing a list inside a list? What happens if you make your result a String?

这篇关于我可以存储列表吗?共同偏好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆