Home > other >  In flutter I am unable to connect to API, When I test it works well but from flutter it is not worki
In flutter I am unable to connect to API, When I test it works well but from flutter it is not worki

Time:05-24

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

CodePudding user response:

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';

And... for the type cast issue, try this instead:

int.parse(prediction["predicted_cluster"][0] as String);

CodePudding user response:

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.

  • Related