我将对象设置为:{“name”:“alex”,“code”:“123”}
进入sharedPrefrence Calss A:
var resBody = {};
resBody["name"] = name.text;
resBody["code"] = pass.text;
str = json.encode(resBody);
print(str);
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("list_customer", str);
当在另一个类中获得此sharedPrefrence时
将共享的值(value)添加到列表B类:
customer = (prefs.getString('list_customer'));
Map<String, dynamic> user = jsonDecode(customer);
_customer.nameFamily = user['name'];
_customer.code = user['code'];
_list.add(_customer);
而且我想知道如何像这样在以前的列表中设置共享的新值:
[{“name”:“alex”,“code”:“123”},{“name”:“john”,“code”:“128”}]
最佳答案
要存储多个客户,您需要一个List
而不是Map
。
List
List<Map<String, dynamic>> customers = [];
final customer = {
"name": name.text,
"code": pass.text,
};
customers.add(customer);
customers
列表final customersString = json.encode(customers);
customers
列表SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("list_customer", customersString);
假设您存储了一个客户,而现在又需要存储另一个客户。
customers
列表,然后我们对其解码String customersString = await prefs.getString('list_customer');
final customers = json.decode(customersString);
customers.add({
"name": 'Amir',
"code": 'SWF2022',
});
祝好运
关于flutter - flutter 增加值(value)到名单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60475345/