颤抖地为列表增加价值

时间:2020-03-01 12:58:50

标签: flutter dart

我将对象设置为:{“ 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时 将共享的价值添加到列表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”}]

2 个答案:

答案 0 :(得分:0)

在下面查看示例

$key+=1;

答案 1 :(得分:0)

要存储多个客户,您需要List而不是Map

  1. 声明一个List
List<Map<String, dynamic>> customers = [];
  1. 将对象添加到列表中
final customer = {
  "name": name.text,
  "code": pass.text,
};

customers.add(customer);
  1. Stringfy(编码)customers列表
final customersString = json.encode(customers);
  1. 存储编码的customers列表
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("list_customer", customersString);

假设您存储了一位客户,现在您需要存储另一位客户。

  1. 我们首先获得customers列表,然后对其进行解码
String customersString = await prefs.getString('list_customer');
final customers = json.decode(customersString);
  1. 将新对象添加到列表中(上一步#2)
customers.add({
  "name": 'Amir',
  "code": 'SWF2022',
});
  1. 重复步骤3和#4。

祝你好运