我使用以下類(一個單獨的 dart 檔案)來提供 API 服務:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Services {
static Future<http.Response> login(String username, String password) async {
var url = "https://10.0.2.2:5001/api/Login/LoginSystem";
Map data = {"Username": username, "Password": password};
var body = json.encode(data);
var response = await http.post(Uri.parse(url),
headers: {
"content-type": "application/json",
"accept": "application/json"
},
body: body);
print(response.statusCode);
print(response.body);
return response;
}
}
我使用以下代碼呼叫服務函式:
onPressed: () {
var response = Services.login("fa2020", "123");
if (response.statusCode == 200) {
showDialog<String>(
context: context,
builder: (BuildContext context) =>
const AlertDialog(
title: Text("ALert"),
content: Text(response.body),
));
}
}
我的問題是我無法訪問最后一個代碼中的response.statusCodeand response.body。我該如何解決?
uj5u.com熱心網友回復:
async-await在onPressed回呼中使用Service.login以異步方式執行。
onPressed: () async {
var response = await Services.login("fa2020", "123");
// ...
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510750.html
標籤:扑镖http
