面临共享偏好波动的问题

时间:2019-08-30 05:40:27

标签: flutter sharedpreferences

我正在使用shared preferences保存来自rest API的商店ID。但是问题是它总是使用相同的商店ID,我想为不同的数据显示不同的商店ID。

Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

Future<bool> _setCategoryId(String keyString, String categoryId) async {
  print("Testing val :: SET ==> keyString "+keyString);
  print("Testing val :: SET : token ==> "+categoryId);
  final SharedPreferences prefs = await _prefs;
  return prefs.setString(keyString, categoryId);
}

Future<String> _getCategoryId(String keyString) async {
  print("Testing val :: GET ==> "+keyString);
  final SharedPreferences prefs = await _prefs;
  return prefs.getString(keyString) ?? '';
}

这是我要保存商店ID的回复

  {success: true, data: [{store_id: 0, name: Bag, store_geocode: , longitude: , latitude: , store_address: Midori-Ku, Yokohama-Shi, Japan, store_telephone: 123456789, thumb: http://yourdomainname.com/image/cache/no_image-500x500.png}, {store_id: 1, name: Asian Spice Market, store_geocode: , longitude: , latitude: , store_address: Yokohama Shi, Naka ku, Noge cho 3-160-4, store_telephone: 0804053636, thumb: http://yourdomainname.com/image/cache/catalog/stores/asian_spice_market/asian_spice_market_logo-500x500.png}]}

1 个答案:

答案 0 :(得分:1)

我认为您正在尝试设置和获取字符串列表。请参见下面的代码。
步骤1:解析您的json字符串以存储列表。底部的代码
第2步:让循环商店列表获取商店ID并添加到myListOfIntegers

如果您的商店ID为int。您可以使用以下代码段,请参见示例2

myListOfIntegers.map((i)=>i.toString()).toList() 

转换为字符串。

商店ID可以是字符串或json字符串

List<String> myListOfStrings=  ["1","2","3","4"]; 
List<String> myListOfJsonStrings=  ['{ "storeid":"123",  "storename":"jock"}',' {  "storeid":"456",  "storename":"abc"}' ];

使用prefs.setStringList和prefs.setStringList

完整代码

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(new MaterialApp(
    home: new Scaffold(
      body: new Center(
        child: new RaisedButton(
          onPressed: _save,
          child: new Text('Save my list of int'),
        ),
      ),
    ),
  ));
}

_save() async {
  List<String> myListOfStrings=  ["1","2","3","4"];

  List<String> myListOfJsonStrings=  ['{ "storeid":"123",  "storename":"jock"}',' {  "storeid":"456",  "storename":"abc"}' ];

  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setStringList('mylist', myListOfStrings);

  List<String> myList = (prefs.getStringList('mylist') ?? List<String>()) ;
  print('Your list  $myList');

  await prefs.setStringList('myjsonlist', myListOfJsonStrings);

  List<String> myjsonList = (prefs.getStringList('myjsonlist') ?? List<String>()) ;
  print('Your list  $myjsonList');
}

结果是

I/flutter (31495): Your list  [1, 2, 3, 4]
I/flutter (31495): Your list  [{ "storeid":"123",  "storename":"jock"},  {  "storeid":"456",  "storename":"abc"}]

示例2:如果您的商店ID为int

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(new MaterialApp(
    home: new Scaffold(
      body: new Center(
        child: new RaisedButton(
          onPressed: _save,
          child: new Text('Save my list of int'),
        ),
      ),
    ),
  ));
}

_save() async {

  List<int> myListOfIntegers = [1,2,3,4];
  List<String> myListOfStrings=  myListOfIntegers.map((i)=>i.toString()).toList();

  SharedPreferences prefs = await SharedPreferences.getInstance();
  List<String> myList = (prefs.getStringList('mylist') ?? List<String>()) ;
  List<int> myOriginaList = myList.map((i)=> int.parse(i)).toList();
  print('Your list  $myOriginaList');
  await prefs.setStringList('mylist', myListOfStrings);
}

您的json字符串

{
"success": true, 
"data": [
    {"store_id": 0, 
"name": "Bag", 
"store_geocode": "", 
"longitude": "", 
"latitude": "", 
"store_address": "Midori-Ku, Yokohama-Shi, Japan", 
"store_telephone": "123456789", 
"thumb": "http://yourdomainname.com/image/cache/no_image-500x500.png}, {store_id: 1, name: Asian Spice Market, store_geocode: , longitude: , latitude: , store_address: Yokohama Shi, Naka ku, Noge cho 3-160-4, store_telephone: 0804053636, thumb: http://yourdomainname.com/image/cache/catalog/stores/asian_spice_market/asian_spice_market_logo-500x500.png"

    }
]
}

使用

解析您的json字符串
// To parse this JSON data, do
//
//     final store = storeFromJson(jsonString);

import 'dart:convert';

Store storeFromJson(String str) => Store.fromJson(json.decode(str));

String storeToJson(Store data) => json.encode(data.toJson());

class Store {
    bool success;
    List<Datum> data;

    Store({
        this.success,
        this.data,
    });

    factory Store.fromJson(Map<String, dynamic> json) => new Store(
        success: json["success"],
        data: new List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "success": success,
        "data": new List<dynamic>.from(data.map((x) => x.toJson())),
    };
}

class Datum {
    int storeId;
    String name;
    String storeGeocode;
    String longitude;
    String latitude;
    String storeAddress;
    String storeTelephone;
    String thumb;

    Datum({
        this.storeId,
        this.name,
        this.storeGeocode,
        this.longitude,
        this.latitude,
        this.storeAddress,
        this.storeTelephone,
        this.thumb,
    });

    factory Datum.fromJson(Map<String, dynamic> json) => new Datum(
        storeId: json["store_id"],
        name: json["name"],
        storeGeocode: json["store_geocode"],
        longitude: json["longitude"],
        latitude: json["latitude"],
        storeAddress: json["store_address"],
        storeTelephone: json["store_telephone"],
        thumb: json["thumb"],
    );

    Map<String, dynamic> toJson() => {
        "store_id": storeId,
        "name": name,
        "store_geocode": storeGeocode,
        "longitude": longitude,
        "latitude": latitude,
        "store_address": storeAddress,
        "store_telephone": storeTelephone,
        "thumb": thumb,
    };
}