我正在Flutter中创建应用程序,在其中我需要保存通过JSON格式的共享首选项来自textinput的数据。我在dart中搜索了有关JSON序列化的信息,然后将其保存到共享的首选项中 我创建了一个用于序列化JSON的Model类,如下所示:
class ServerData {
final String servername;
final String serverurl;
final String username;
final String password;
ServerData(this.servername, this.serverurl, this.username, this.password);
ServerData.fromJson(Map<String, dynamic> json)
: servername = json['servername'],
serverurl = json['serverurl'],
username = json['username'],
password = json['password'];
Map<String, dynamic> toJson() => {
'servername' : servername,
'serverurl' : serverurl,
'username' : username,
'password' : password
};
}
现在我需要在TextEditingController的帮助下存储输入数据:
final _servername = TextEditingController();
final _serverurl = TextEditingController();
final _username = TextEditingController();
final _password = TextEditingController();
ServerData serverData = new ServerData(_servername.text,_serverurl.text,_username.text,_password.text);
/* I am getting error of "Only static members can be accessed in Initializers" in above code */
String encodeData = jsonEncode(serverData); /* Not able to use encode and decode due to error in ServerData object */
我需要有关此的帮助。
答案 0 :(得分:1)
您必须在initState
内部移动初始化:
ServerData serverData;
String encodeData;
@override
void initState() {
serverData = new ServerData(_servername.text,_serverurl.text,_username.text,_password.text);
encodeData = jsonEncode(serverData);
super.initState();
}