Flutter send json body in Http GET Method - json

i tried many solutions but it still give me the same error :
"Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>?'"
Future<GetCustomerList> _getStateList() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
var token = prefs.getString("userToken");
final String url = "http://194.195.245.189:8069/get_partners?params: {}";
Map<dynamic, dynamic> qParams = {
"params": {}
};
Map<String, String> headers = {'Cookie':'session_id=$token',
'Content-Type':'application/json; charset=UTF-8'};
var customerList = await http.get(Uri.parse(url),headers: headers,body: qParams);
if (customerList.statusCode == 200) {
return GetCustomerList.fromJson(json.decode(customerList.body));
} else {
throw Exception('Failed to load Customers');
}
}

you have to convert your result into a map take inspiration from this link
Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>

Related

_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>

i got an error and this is my API wrapper
if (method == "get") {
var param = '';
Map<String, dynamic> params =
data['params'] != null ? data['params'] : {};
params.forEach((k, v) => param += k + "=" + (v == null ? '' : v) + "&");
try {
Dio dio = new Dio();
dio.options.headers = headers;
final response = await dio.get(url + "?" + param);
responseJson = _response(response);
//print('Response ' + response.data.toString());
} on SocketException {
throw FetchDataException('Tidak terhubung ke server');
}
. . .
and this is the repository:
Future<LeaveListModel> fetchResponse(query) async {
final response = await _wrapper.apiRequest(
"get", _wrapper.leaveListGetData, {'params': query}, true);
return LeaveListModel.fromJson(response);
}
this is the service, in case you wanted to know:
class Service {
GetStorage localData = GetStorage();
final String initial = "Service";
final String baseUrl = ConstantConfig().leaveListEndPoint;
final String appCode = ConstantConfig().leaveListAppCode;
final String outputType = "json";
final String routeAuthConnect = "auth/connect/";
final String routeAuthGetAccessToken = "auth/getAccessToken/";
final String leaveListGetData = "list/";
Future<dynamic> apiRequest(
String method, String route, Map<String, dynamic> data,
[bool needToken = false]) async {
ApiWrapper _apiWrapper = ApiWrapper();
if (needToken) {
int thisTime = (DateTime.now().millisecondsSinceEpoch / 1000).round();
String? savedExpired = localData.read(initial + KeyStorage.accessExpired);
int expire = savedExpired == null ? 0 : int.parse(savedExpired);
if (expire < thisTime) {
dynamic tokenResponse = await _apiWrapper.request(baseUrl, initial,
appCode, outputType, 'post', routeAuthGetAccessToken, {});
await localData.write(initial + KeyStorage.accessToken,
tokenResponse['response']['access_token']);
return await _apiWrapper.request(
baseUrl, initial, appCode, outputType, method, route, data);
} else {
return await _apiWrapper.request(
baseUrl, initial, appCode, outputType, method, route, data);
}
} else {
return await _apiWrapper.request(
baseUrl, initial, appCode, outputType, method, route, data);
}
}
}
i just want to call a json file but it show an error, i don't know what's wrong with my code, in case you know how to fix it please let me know
this is the error:
I/flutter (20696): Call https:xxxxxxxxxxxx
I/flutter (20696): type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'
another error note:
I/flutter ( 7626): {}
I/flutter ( 7626): 1
I/flutter ( 7626): type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'
I/flutter ( 7626): {}
I/flutter ( 7626): 1
I/flutter ( 7626): type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'
actually that shows that the process is stopped on Map<String, dynamic> params = data['params'] != null ? data['params'] : {}; because i try to debug the API wrapper with print('1');, print('2');, print('3'); just to show where the process stop and getting error
You need decode your response first then use it:
LeaveListModel.fromJson(jsonDecode(response));
also I think you are passing query encoded to ApiWrapper, so you need to decode it like this:
Map<String, dynamic> params = data['params'] != null ? jsonDecode(data['params']) : {};
return LeaveListModel.fromJson(response);
It seems to me that you should use response.data here, instead of response.
return LeaveListModel.fromJson(response.data);
Try this:
Map<String, dynamic>.from(yourData)
For Map<String, dynamic> json, parse like this
List<Blog> blogs = (json['blogs'] as List<dynamic>).map((e) => Blog.fromJson(e as Map<String, dynamic>)).toList();

nhandled Exception: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'call'

I am facing an issue when data is fetched from the api and is not mapped into the model and the following error is thrown I have also posted the BodyModel class which contains the fromJson function:
Future<BodyModel> fetchJson(http.Client client, String? id) async {
final response = await client.get(
Uri.parse(uri2),
);
if (response.statusCode == 200) {
String jsonData = response.body;
print(response.body);
//print(jsonEncode(response.body));
BodyModel alpha = responseJSON(jsonData);
//print(alpha.toSet());
//bravo = alpha;
return alpha;
} else {
throw Exception('We were not able to successfully download the json data.');
}
}
BodyModel responseJSON(String response) {
final parse = jsonDecode(response);
print(parse.toString());
final resp = parse<BodyModel>((json) => BodyModel.fromJson(json));
print(resp);
return resp;
}
import 'package:flutter/material.dart';
class BodyModel {
String body;
String title;
BodyModel({
required this.body,
required this.title,
});
factory BodyModel.fromJson(Map<String, dynamic> jsonData) {
return BodyModel(
body: jsonData['body'].toString(),
title: jsonData['title'].toString(),
);
}
}
You are calling parse<BodyModel>(...).
It's not clear what you think that's supposed to do, but parse is a variable containing a Map<String, dynamic>, not a generic function.
It has type dynamic, so you won't get any warnings when misusing it.
Consider declaring parse as
Map<String, dynamic> parse = jsonDecode(response);
so it has the correct type.
From the return type of responseJSON, my guess is that you want to do:
final resp = BodyModel.fromJson(parse);

how to filter Json data and use other methods | function | classes? How get Json data into list?

Future<List<AdMob>>getData() async {
final String url =
"https://raw.githubusercontent.com/awais939869/AdsJson/main/speedifypro.json";
http.Response response = await http.get(Uri.parse(url));
// http.Response response = await http.get(Uri.parse("https://raw.githubusercontent.com/Hammad46/app/main/admob.json"));
var jsonObject = json.decode(response.body);
List <dynamic> data = (jsonObject as Map<String, dynamic>)['AdMob'];
List <AdMob> listData = [];
for (int i=0; i<data.length; i++)
listData.add(AdMob.fromJson(data[i]));
return listData;
}
ERROR
E/flutter ( 6315): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List'
JSON data
{
"AdMob": {
"Banner": "true",
"Interstitial": "true"
}
}
AdMob is not a List. it's a map. so if you want your code to work without problem your JSON should be like following:
{
"AdMob": [
{
"Banner": "true",
"Interstitial": "true"
}
]
}

Flutter - type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'

I'm just new in flutter and I think this is a newbie question.
I'm trying to get the data that I call on my API and save it to my model but it's having an error type 'List' is not a subtype of type 'Map<dynamic, dynamic>'
Here is the copy of my model
class AdTemplate{
final int id;
final String filePath;
final String notification;
final String status;
final int whenAdded;
AdTemplate(
{this.id,
this.filePath,
this.notification,
this.status,
this.whenAdded});
factory AdTemplate.fromJson(Map<String, dynamic> json) {
return AdTemplate(
id: json['ID'],
filePath: json['FilePath'],
notification: json['Notification'],
status: json['Status'],
whenAdded: json['WhenAdded']
);
}
}
And this is my function
Future<AdTemplate> getActiveBannerNotif() async {
try {
String url = 'https://api/path/';
var res = await http.get(url);
final Map data = convert.jsonDecode(res.body);
if (res.statusCode == 200) {
print("Data Fetch!");
AdTemplate template = AdTemplate.fromJson(data);
return template;
} else {
print('No data.');
return null;
}
} catch (e) {
print(e);
return null;
}
}
This is the sample data that I get from the API
[{"ID":49,"FilePath":"20210903t171244.png","Notification":"ACT","WhenAdded":1630689165,"Status":"INA"}]
API returns JSON array not json object so that is List not Map.
try :
if (res.statusCode == 200) {
print("Data Fetch!");
AdTemplate template = AdTemplate.fromJson(json.decode(utf8.decode(res.bodyBytes)));
return template;
}
You are receiving an array from your API and that causes the error. change as following to access a single element from array
Future<AdTemplate> getActiveBannerNotif() async {
try {
String url = 'https://api/path/';
var res = await http.get(url);
if (res.statusCode == 200) {
print("Data Fetch!");
final data = convert.jsonDecode(res.body);
AdTemplate template = AdTemplate.fromJson(data[0]);
return template;
} else {
print('No data.');
return null;
}
} catch (e) {
print(e);
return null;
}
}
Your api return a List
[{"ID":49,"FilePath":"20210903t171244.png","Notification":"ACT","WhenAdded":1630689165,"Status":"INA"}]
Try to get data like that: data[0] or data.first before convert into model

How to convert file object to encodable json object in flutter?

Im trying to map profilePicture to a File object using dart , i have the profilePicture saved as IFormFile in the c# backend..
This is the mapping function and other functions in my ManageUserModel class:
Map<String, dynamic>toMap() {
return {
"profilePicture":profilePicture,
(other mappings)
}
}
List<ManageUserModel> fromJson(String jsonData) {
// Decode json to extract a map
final data = json.decode(jsonData);
return List<ManageUserModel>.from(
data.map((item) => ManageUserModel.fromJson(item)));
}
String toJson(ManageUserModel data) {
// First we convert the object to a map
final jsonData = data.toMap();
// Then we encode the map as a JSON string
return json.encode(jsonData);
}
Note that profilePicture is one of the ManageUserModel attributes and is of type File .
When the http update request is invoked via this method:
Future<String> updateUser(ManageUserModel data) async {
final response = await client.put("$baseUrl/Users",
headers: {"content-type": "application/json"},
body: toJson(data),
);
if (response.statusCode == 200) {
return "Success";
} else {
return "Fail";
}
}
i get this error:
E/flutter (10061): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Converting object to an encodable object failed: Instance of '_File'
Any help ?
From the error you've provided, it looks like you're trying to map '_File' object as a json.
E/flutter (10061): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Converting object to an encodable object failed: Instance of '_File'
That won't do since fromJson can only handle Maps. What you may want to consider is to store the file as an image URL, or as what have been previously mentioned in the comments - as base64.