问题:
无法使用共享首选项将新值附加到List<String>
。新值将为String
类型。
这是我的定义和方法:
List<dynamic> deliveryAddressConfirmed = new List(5);
SharedPreferences prefs;
:
: //does something here...& on a specific condition call for gotNewNiceAddress(xxxx);
:
gotNewNiceAddress(dynamic capturedNewAddress) async {
print(capturedNewAddress);
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString("deliveryAddressConfirmed", capturedNewAddress);
var x = deliveryAddressConfirmed.length;
print("New length = $x");
setState(() {
deliveryAddressConfirmed =
prefs.getStringList('deliveryAddressConfirmed');
});
}
控制台输出:
D/ViewRootImpl(17086): ViewPostImeInputStage ACTION_DOWN
I/flutter (17086): Mountain valley, north 16th street, JC -20293
I/flutter (17086):
I/flutter (17086):
I/flutter (17086): New length = 0
不知道我在上面的代码中是否做错了什么。有人可以帮忙吗?
答案 0 :(得分:0)
您使用"Sunline-Pool-1(Sunline-job-server)-thread-2" #136 prio=5 os_prio=0 tid=0x00007f0fa4003000 nid=0x586e runnable [0x00007f0f03bcb000]
java.lang.Thread.State: RUNNABLE
at java.io.UnixFileSystem.getBooleanAttributes0(Native Method)
at java.io.UnixFileSystem.getBooleanAttributes(UnixFileSystem.java:242)
at java.io.File.exists(File.java:819)
"Sunline-Pool-1(Sunline-job-server)-thread-3" #137 prio=5 os_prio=0 tid=0x00007f0fa4005000 nid=0x5871 runnable [0x00007f0f03aca000]
java.lang.Thread.State: RUNNABLE
at java.io.UnixFileSystem.getBooleanAttributes0(Native Method)
at java.io.UnixFileSystem.getBooleanAttributes(UnixFileSystem.java:242)
at java.io.File.exists(File.java:819)
保存了一个字符串,但是当您使用prefs.setString
进行读取时,则需要一个字符串列表。
那是行不通的。您应该阅读所写内容。我不知道你要什么一个字符串?字符串列表?但是,您只能准确地阅读您所输入的内容。您的决定。
如果要添加到现有列表,则必须阅读列表,追加到列表中,然后再次将其另存为列表。
prefs.getStringList
答案 1 :(得分:0)
我不知道您要达到什么目的,但是要在列表中添加一些内容,然后您 做下面的事情
deliveryAddressConfirmed.add(prefs.getStringList('deliveryAddressConfirmed'));
此外,您在添加列表之前先打印列表,因此它将始终打印0。 尝试在setState之后调用print语句。