Dart unable to parse JSON from string to int - flutter

I am trying to parse a JSON value from string to int but got stuck :(
The code below shows a HTTP get request and retrieving a JSON object in which I want to obtain the 'reps' value in Integer.
var response = await httpClient.get(url, headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'X-API-Key': apikey
});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
var res = json.decode(response.body);
String repStr = res['reps'];
print(repStr);
int repInt = int.parse(repStr);
The debug console shows the following error on the line
String repStr = res['reps'];
E/flutter ( 8562): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'int' is not a subtype of type 'String'

As the exception explains, the value res['reps'] is already an integer you don't need to parse it.
int repStr = res['reps'];

Related

The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr<UserModel> and can't be assigned to type 'Uri'

I am getting two errors in the below code.
The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr', is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
The argument type 'String' can't be assigned to the parameter type 'Uri'.
import 'dart:convert';
import 'package:altamazee/models/user_model.dart';
import 'package:http/http.dart' as http;
class AuthService {
String baseUrl = 'https://shamo-backend.buildwithangga.id/api';
Future<UserModel> register({
required String name,
required String username,
required String email,
required String password,
}) async {
var url = '$baseUrl/register';
var headers = {'Content-Type': 'application/json'};
var body = jsonEncode({
'name': name,
'username': username,
'email': email,
'password': password,
});
var response = await http.post(
url,
headers: headers,
body: body,
);
if (response.statusCode == 200) {
var data = jsonDecode(response.body)['data'];
UserModel user = UserModel.fromJson(data['user']);
user.token = 'Bearer ' + data['access_token'];
return user;
}
}
}
The first error occurs on the line Future<UserModel> register({. The second error is on the line with http.post.
The first error is because you don't return anything if your http.post request isn't successful. You can fix this by returning something even if the post request fails, such as using Future<UserModel?> as the return type (null if no UserModel is returned), by returning an empty UserModel, or by throwing an error.
The second error is because the first parameter for http.post is a Uri, not a string. Build your Uri according to the example here: http package example.
final url = Uri.https('https://shamo-backend.buildwithangga.id', '/api/register');
First error says what if you haven’t get any response due to error!
You only checked for 200 status code. If error happens then this block
if(response.statusCode == 200) will not be executed.
So, there is nothing to return! You may write like this,
if(response.statusCode == 200)
{
// your code
}
return null; //this will execute if error occurs
But doing this will show an error because your return type is, Future<UserModel>.
So, change it to Future<UserModel?> will fix the first error!
Second Error
This worked previously, but now http needs Uri type instead of String.
Doing like this will fix your error,
var response = await http.post(
Uri.parse(url),
headers: headers,
body: body,
);

Unable to send header information with client.post

I'm trying to pass along a bearer token and refresh token to an endpoint in Flutter but I'm getting errors no matter what I try. The api endpoint does work with Postman and returns a new token so the issue is with Flutter.
Future<List<PetsList>> fetchPets(http.Client client) async {
var _headers = {
'Content-Type': 'application/json',
'token': singleton.token,
'refreshToken': singleton.refreshToken,
};
var encodedHeader = json.encode(json.encode(_headers));
final response = await client.post(
Uri.parse(baseUrl + '/account/refreshtoken'),
headers: encodedHeader);
print("${response.body}");
};
This threw an error and stated that "The argument type 'String' can't be assigned to the parameter type 'Map<String, String>?'"
So I appended encodedHeader as Map<String, String> in the response
encodedHeader as Map<String, String>
but that then threw another error, "_CastError (type 'String' is not a subtype of type 'Map<String, String>' in type cast)"
Lastly, the response.body throws an error when I try to simply
print("${response.body}");
and states "Object reference not set to an instance of an object."
No matter what I've tried Flutter complains about this, I seem to be going in circles on this one and could use some help.
The headers require a map<string, string> if you json encode it then it becomes a single string. Please remove the encode
Future<List<PetsList>> fetchPets(http.Client client) async {
Map<String, String> _headers = {
'Content-Type': 'application/json',
'token': singleton.token,
'refreshToken': singleton.refreshToken,
};
final response = await client.post(
Uri.parse(baseUrl + '/account/refreshtoken'),
headers: _headers);
};

In flutter I am unable to connect to API, When I test it works well but from flutter it is not working?

Future predictCluster(List<List<int>> scores) async {
String url = 'http://127.0.0.1:5000/predict';
Uri uri = Uri.parse(url);
Response response = await post(uri, body: (scores));
Map<String, dynamic> prediction = json.decode(response.body);
cluster = int.parse(prediction["predicted_cluster"][0]);
notifyListeners();
}
Here I have to send a list of list with integers as per API but getting rejected by casting when I am using encode methods I am getting a Format exception.
This is the api.
Getting Error for line
Response response = await post(uri, body: (scores));
Error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'List' is not a subtype of type 'int' in type cast
The problem is, probably, that your emulator doesn't reach your API on your local machine.
The url should instead be:
String url = 'http://10.0.2.2:5000/predict';
Future predictCluster(List<List<int>> scores) async {
String url = 'http://10.0.2.2:5000/predict';
Uri uri = Uri.parse(url);
final encodedData = jsonEncode(<String, dynamic>{
"score": scores,
});
Response response = await post(
uri,
headers: {"Content-Type": "application/json"},
body: encodedData,
);
Map<String, dynamic> prediction = json.decode(response.body);
cluster = int.parse(prediction["predicted_cluster"][0]);
notifyListeners();
}
We have to send through the map structure to encode data and also mention the header content type to application/json.

How can pass the request parameter as a formdata in dart or flutter

I have tried many formats to pass the request parameter in the flutter project but I'm getting API status code 415 and Unhandled Exception: FormatException: Unexpected end of input (at character 1).
I have added the postman image for the understanding of the form data.
For Flutter HTTP library it goes like this,
var headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var request = http.Request('POST', Uri.parse(''));
request.bodyFields = {
'firstName': 'Keval',
'lastName': 'ebiz',
'email': 'al#gmail.com',
'phone': '1234'
};
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}

The getter 'length' was called on null in post request

I'm trying to make a post request to an API, and I couldn't get why this is happening.
This is my code:
print('THIS IS PRINTING');
var response = await http.post(url, body: body, headers: header);
print('This not printing (throwing error before it prints)');
This is the error that I'm getting:
I/flutter ( 2417): NoSuchMethodError: The getter 'length' was called on null.
I/flutter ( 2417): Receiver: null
I/flutter ( 2417): Tried calling: length
I'm able to make the request using PostMan, and giving the same fields and values, I get this error on dart. I'm also able to make other get requests without any issues.
Full code:
void getFavorites() async {
var url = "https://www.my-url-edited.com/favorite";
var header = {
"Content-Type": "application/x-www-form-urlencoded",
"token": "my token ---- edited",
};
var body = {
"car_id": "1",
"boat_id": null,
"habitation_id": null,
"product_id": null,
};
try {
print('print before post request --- working');
// var response = await http.post(url, body: body, headers: header);
var response = await http.post(url, body: body, headers: header);
print('This not printing (throwing error before it prints)');
print(response.body);
// var data = json.decode(response.body);
} catch (e) {
print(e);
throw Exception('Not connected to network');
}
}
you header should be ,
headers: {'Content-type': 'application/json','Accept': 'application/json'}
Try
var header = {
"Content-Type": "application/json",
"token": "my token ---- edited",
};
var body = jsonEncode({
"car_id": "1",
});