I use the following class (a separate dart file) to provide API services:
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;
}
}
And I use the following code to call the service function:
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),
));
}
}
My problem is that I cannot access the response.statusCode
and response.body
in the last code. How can I fix it?
CodePudding user response:
Use async-await
in onPressed
callback as Service.login
executes in async manner.
onPressed: () async {
var response = await Services.login("fa2020", "123");
// ...
},