[英]Flutter - Http Json Response
我正在試用flutter ,我已經連接了一個http 帖子用於登錄。
我創建了一個文件來處理我的http 請求。 在文件中寫了以下代碼:
Map data;
Future<Map> logIn(email, password) async {
String url = "...";
Object userData = { "email": email, "password": password };
var userDataBody = JSON.encode(userData);
Map userHeader = {"Content-type": "application/json", "Accept": "application/json"};
http.Response response = await http.post(
Uri.encodeFull(url),
headers: userHeader,
body: userDataBody
);
data = JSON.decode(response.body);
print(data);
return data;
}
Http返回如下數據:
{message: Login Successful, status: success}
上面的代碼用於有狀態的小部件:
// imported the file above as userService
import 'services/user_services.dart' as userService;
// created a method for a button
void submitData() {
final form = formKey.currentState;
if (form.validate()) { // no validations so far
form.save(); // save email and password
userService.logIn("$userEmail", "$userPassword"); // .then(JSON.decode(responseContent['message']));
}
}
// button in container
new Container(
padding: new EdgeInsets.all(20.0),
child: new RaisedButton(
onPressed: submitData,
child: new Text('LogIn'),
)
),
我的問題是,對於返回的 json 數據,我正在努力獲取返回的狀態(成功)/消息(登錄成功)並隨心所欲地處理它們。
不知道問題是什么,但我猜你想要的是什么
void submitData() async {
...
var result = await userService.logIn("$userEmail", "$userPassword");
}
這樣你就可以掌握結果。 如果這是您正在尋找的,則無法從異步調用中恢復同步。
您可以使用
data = jsonDecode(response.body)
對於個別內容,使用data["message"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.