我可以存储具有共享首选项的List <dynamic>吗?

时间:2019-04-19 12:49:40

标签: dart flutter

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

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);

}

我希望看到这样的列表 [{ProductID:155,名称:Multi-vit,说明:Multi-vit,CostPrice:0.0,SalePrice:80,EatOutPrice:80,CategoryID:976,Barcode:,TaxRateID:null,}]

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

一种简单的方法是将Php编码为JSON并将其另存为字符串。

List
相关问题