我的登录屏幕第一次出现抖动,我尝试了多种解析json的方法,但到目前为止都没有成功。谁能帮我得到json的回复,以便我也能对此有所了解。
---my model class
class User{
String email;
String password;
String token;
User({
this.email,
this.password,
this.token
});
factory User.fromJson(Map<String, dynamic> parsedJson){
// Map json = parsedJson['user'];
return User(
email: parsedJson['email'],
password: parsedJson['password'],
token: parsedJson['token']
);
}
}
-------
json for response.
Future loadUser() async{
final response = await http.get(url, headers : {
HttpHeaders.contentTypeHeader: 'application/json'
}
body : User.fromJson(response);
print(user.token);
);
enter code here
}
-----
{
"email": "zxc@example.com",
"password": "aa718893bfe3e587047c81af40269d14",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6Mn0.MGBf"
}
答案 0 :(得分:2)
您可以使用
解析JSON字符串final user = userFromJson(jsonString);
或使用userToJson函数将用户对象转换为json字符串
用户分类代码
// To parse this JSON data, do
//
// final user = userFromJson(jsonString);
import 'dart:convert';
User userFromJson(String str) => User.fromJson(json.decode(str));
String userToJson(User data) => json.encode(data.toJson());
class User {
String email;
String password;
String token;
User({
this.email,
this.password,
this.token,
});
factory User.fromJson(Map<String, dynamic> json) => new User(
email: json["email"],
password: json["password"],
token: json["token"],
);
Map<String, dynamic> toJson() => {
"email": email,
"password": password,
"token": token,
};
}
答案 1 :(得分:1)
使用Flutter的官方http软件包执行GET和POST操作。
要安装http
软件包,请将其添加到pubspec.yaml
的依赖项部分。您可以在Pub网站上找到http
软件包的最新版本。
dependencies:
http: <latest_version>
要执行GET操作,请调用http.get(),
http.get("http://api.urbandictionary.com/v0/define?term=api").then(
(response) // Server response
{
if(response.statusCode==200) // Checking if the transaction was successful
{
print(response.body);// Your response body
}
else print("The transaction was unsuccessful");
}
);
如果您想解析json请求,
https://flutter.dev/docs/cookbook/networking/background-parsing
答案 2 :(得分:1)
Future loadUser() async{
final response = await http.get(url,
headers : { HttpHeaders.contentTypeHeader: 'application/json' }
Map<String,dynamic> parsedJson = json.decode(response.body);
body : User.fromJson(parsedJson);
);
}