将列表保存到SharedPreferences

时间:2020-08-07 16:35:46

标签: flutter dart

我正在尝试保存从sql拖放到SharedPreferences的列表,我尝试使用以下代码:

static Future<List<User>> getUsers() async {
    final myUserId = await getUser();
    try {
      var myUser = myUserId;
      var map = Map<String, dynamic>();
      map['user'] = myUser;
      final response = await http.post(ROOT, body: map);
      //print('getUsers Response: ${response.body}');
      //print(myUser);
      if (200 == response.statusCode) {
        List<User> listContacts = parseResponse(response.body);
        SharedPreferences contacts = await SharedPreferences.getInstance();
        contacts.setStringList('contacts', listContacts);
        return listContacts;
      } else {
        return List<User>();
      }
    } catch (e) {
      return List<User>(); // return an empty list on exception/error
    }
  }

列表的User类如下:

class User {
  final String firstName;
  final String lastName;
  final String imageLink;

  User({this.firstName, this.lastName, this.imageLink});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      firstName: json['firstName'] as String,
      lastName: json['lastName'] as String,
      imageLink: json['imageLink'] as String,
    );
  }
}

因此,基本上,数据已成功从数据库中拉出并显示了它,但是我想将数据保存到SharedPreferences,因此不必每次都加载。发生的错误是listContacts无法分配给setStringList,因为它是List<User>而不是List<String>,但是我不知道如何否则我可以更改代码以设置SharedPreferences

1 个答案:

答案 0 :(得分:0)

您可以在这里做

static Future<List<User>> getUsers() async {
final myUserId = await getUser();
try {
  var myUser = myUserId;
  var map = Map<String, dynamic>();
  map['user'] = myUser;
  final response = await http.post(ROOT, body: map);
  //print('getUsers Response: ${response.body}');
  //print(myUser);
  if (200 == response.statusCode) {

    List<User> listContacts = parseResponse(response.body);
    SharedPreferences contacts = await SharedPreferences.getInstance();
    contacts.setString('contacts',json.encode(response.body)); //Here saved the response
    return listContacts;
  } else {
    return List<User>();
  }
} catch (e) {
  return List<User>(); // return an empty list on exception/error
}


 }

现在可以使用它了

SharedPreferences contacts = await SharedPreferences.getInstance();
var response = json.decode(contacts.getString('contacts'));
List<User> listContacts = parseResponse(response.body);

您会从共享的首选项中获取数据