Reputation: 143
Making my login screen in flutter for first time and i have tried many ways to parse json but none of worked till now. can anyone please help me to get response from json so i can also get idea about this.
---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": "[email protected]",
"password": "aa718893bfe3e587047c81af40269d14",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6Mn0.MGBf"
}
Upvotes: 0
Views: 1418
Reputation: 2021
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);
);
}
Upvotes: 1
Reputation: 1679
Use Flutter's official http package to perform GET and POST operations.
To install the http
package, add it to the dependencies section of the pubspec.yaml
. You can find the latest version of the http
package on the Pub site.
dependencies:
http: <latest_version>
To perform GET operation call 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");
}
);
If you want to parse your json request,
https://flutter.dev/docs/cookbook/networking/background-parsing
Reference : https://flutter.dev/docs/cookbook/networking/fetch-data
Upvotes: 1
Reputation: 54367
you can parse your JSON string with
final user = userFromJson(jsonString);
or convert your user object to json string with userToJson function
User class code
// 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,
};
}
Upvotes: 2