I am having an error while trying to make a get request on flutter - flutter

String url = 'http://localhost:9000/user/john.doe#email.com';
Future<String> get makeRequest() async {
var response = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application"});
print(response.body);
}
I get an error on makeRequests() that says "This function has a return type of 'Future', but doesn't end with a return statement."

You have to return data corresponding to the return type of the function.
String url = 'http://localhost:9000/user/john.doe#email.com';
Future<String> get makeRequest() async
{
var response = await http.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
print(response.body);
return(response.body);
}

You must return a String in the function with the header Future< String >. You probably want to return response.body

Related

Flutter type '_SimpleUri' is not a subtype of type 'String' error

This is my simple code
try{
final dynamic headers = await _getReqHeader();
http.Response res = await http.get(Uri.parse(url), headers: headers);
print("Dres2="+res.toString());
return _result(res);
}catch(e){
print("Dres3="+e.toString());
return _result({});
}
This code works well. But when use some url's I get type '_SimpleUri' is not a subtype of type 'String' error. In postman this url works perfectly. I could not find any information about _SimpleUri. How can I solve this problem?
The get method of the http package takes Uri.https(hostUrl , apiEndpoint) not Uri.parse.
The error appears because a simple URLs being passed to it. To fix this, you have to do this:
http.Response res = await http.get(Uri.https(host, url), headers: headers);
I had a similar issue and that's how I solved it.
static const baseUrl = "apihost.com";
Future<http.Response> _get(String url, {host = baseUrl}) async {
final header = <String, String>{};
return http.get(Uri.https(host, url), headers: header);
}
Future<String?> getData() async {
final response = await _get("/endpoint");
if (isSuccessful(response)) {
final json = jsonDecode(response.body);
} else {
print('GET failed [${response.statusCode}]:
${response.body}');
return null;
}
}

How to fetch string?

I have code like this:
Future<http.Response> makeRequest() async {
return await http.get(Uri.parse(url));
}
my "url" is a string, and it is working. From the internet i got string like "10" or "125", but when i use this method in my project and im converting it to string it only writes me an error:
Instance of 'Future Response'
, how can i take my string from the internet?
this is my url:
https://apialgorytm20210606150610.azurewebsites.net/algorytm/5w5
Future<String> getObjectFromAPI() async {
var response = await http.get(Uri.parse('www.myAPI.com/getData'),); //1
if (response.statusCode == 200) { //2
return(jsonDecode(response.body)["yourObjectHere"]); //3
} else {
return 'error';
}
}
Here you go.
Put your API url in line 1.
Line 2 checks if you receive a 200OK return or some kind of error code. Line 3 prints the decoded JSON response from the API, and you can enter the specific object you want to fetch as well
Future makeRequest() async {
var res= await http.get(Uri.parse(url));
If(res.statusCode==200){
print(res.body);
return res.body;}else{return null;}
}
now use the above function
var data=makeRequest();
print(data);

Response body empty API

My response.body return empty like this: Response.body: []
It was supposed to return the param like Response.body:["CodVenda":4057}]
static Future<List<Produto>> iniciaVenda(codVenda) async {
var url = 'http://192.168.0.112:4343/inicia_venda.php';
Map<String, String> headers = {};
final params = {"CodVenda": codVenda};
print("> Params: $params");
print("> Pedido Post POST: $url");
final response = await http.post(url, body: params, headers: headers);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
List list = convert.json.decode(response.body);
final produtos =
list.map<Produto>((map) => Produto.fromJson(map)).toList();
var retornoResponse = false;
I get the data from a API and then I wanted to start the sell but it returns empty.
Could it be a problem in API?
Actually, you need to pass body data with JSON encoded. That may be the main problem.
final response = await http.post(url, body: jsonEncode(params), headers: headers);
You can read more from the official document.

How to Show Snackbar with the Result of Future Http Post?

I'm trying to get a "File was uploaded." string back from a successful Future HTTP post request so that I can create a SnackBar but all I get back from the return is null. Here's the button which calls the Future;
IconButton(
icon: Icon(TriangleAll.upload_3, ),
onPressed: () async {
replyresult = await uploadReply(
filepath: _current.path);
)
if (replyresult != null){
print(replyresult);
}
}
)
And here's the code for the future;
Future<String> uploadReply(
}) async {
final serverurl = "http://example.com/example.php";
final filepath = "examplefilepath";
String serverResponse;
var request = http.MultipartRequest('POST', Uri.parse(serverurl));
var multiPartFile = await http.MultipartFile.fromPath("audio", filepath,
contentType: MediaType("audio", "mp4"));
request.files.add(multiPartFile);
request.send().then((result) async {
http.Response.fromStream(result).then((response) {
if (response.statusCode == 200) {
serverResponse = response.body;
print(serverResponse);
return serverResponse ;
}
});
});
}
I'm trying to use the replyresult variable to create the snackbar upon a successful 200 server response. I know the post is successful as I can see the correct printed serverResponsein the console.
I've tried to simply do;
return response.body ;
But I'm still getting null at the replyresult variable.
because the method returns before the response arrives in Future, do this
var response = await http.Response.fromStream(result);
if (response.statusCode == 200) {
serverResponse = response.body;
print(serverResponse);
return serverResponse ;
} else return '';
or a single await ahead of the Future.
This is what worked.
var multiPartFile = await http.MultipartFile.fromPath("audio", filepath,
contentType: MediaType("audio", "mp4"));
request.files.add(multiPartFile);
final response = await http.Response.fromStream(await request.send());
String serverResponse;
if (response.statusCode == 200) {
String serverResponse = response.body;
print(serverResponse);
return serverResponse;
}

How To deal with Response after post request dart httpClient

So I was having issues with flutter http package when it came to making a post request so I used dart HttpClient. I made a post request according to what was described somewhere but I am having issues getting response. Here is my code
Future<HttpClientResponse> submit() async {
print('start');
Map<String, dynamic> data = { 'title' : 'My first post' };
String jsonString = json.encode(data); // encode map to json
String paramName = 'param'; // give the post param a name
String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString);
List<int> bodyBytes = utf8.encode(formBody); // utf8 encode
HttpClientRequest request =
await HttpClient().postUrl(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
// it's polite to send the body length to the server
request.headers.set('Content-Length', bodyBytes.length.toString());
request.headers.set('Content-Type', 'application/json');
request.add(bodyBytes);
print('done');
return await (request.close());
}
How do I get the response from this request?
HttpClientResponse response = await request.close();
response.transform(utf8.decoder).listen((contents) {
print(data); // <- response content is here
});
This will return HttpCLientResponse, more info https://api.dartlang.org/stable/2.6.1/dart-io/HttpClient-class.html
I have found this from the docs
new HttpClient().get('localhost', 80, '/file.txt')
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) {
response.transform(utf8.decoder).listen((contents) {
// handle data
});
});
Or Use http library
I have create a common method which can handle all get Request,
Future<String> getRequest([var endpoints, var queryParameters]) async {
var uri = Uri.https(NetworkUrl.BASE_URL_1, endpoints, queryParameters);
uri.replace(queryParameters: queryParameters);
var response =
await http.get(Uri.encodeFull(uri.toString()));
//Retrun reponse here
if (response.statusCode == 200) return response.body;
}
To get a response from the above method,
Future<String> deletePostApi() async {
await NetworkRepository()
.getRequest(NetworkUrl.deletePost + '${widget.mFeedData.post_id}')
.then((value) {// <=value is json respone
var dataConvertedToJSON = json.decode(value);
print("checkEmailResp" + dataConvertedToJSON.toString());
});
}