I am creating app in Flutter in which I need to save data coming from textinput through shared preferences in JSON Format. I searched about JSON serialization in dart before saving it to the shared preferences I created a Model class for serializing JSON which is given below :
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
};
}
Now I need to store the input data with the help of 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 */
I need help regarding this.
ServerDatawith empty stringsServerDatain moment when you exactly want to save data. It can by on pressing the button or on changing text inTextField