Searching through List<HashMap<String, dynamic>> and return if it contains value flutter - flutter

Below is how i am fetching my data
static Future<List<Item>> fetchItems(String query) async {
try {
final response = await http.get(
Uri.parse(
"https://api.json-generator.com/templates/ueOoUwh5r44G/data"),
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer tltsp6dmnbif01jy9xfo9ssn4620u89xhuwcm5t3",
}) /*.timeout(const Duration(seconds: Config.responseTimeOutInSeconds))*/;
final List<Item> itemsList;
if (response.statusCode == 200) {
itemsList = json
.decode(response.body)
.map<Item>((json) => Item.fromJson(json))
.where((item) {
final idLower = item.id.toLowerCase();
final titleLower = item.title.toLowerCase();
final subTitleLower = item.subTitle.toLowerCase();
final searchLower = query.toLowerCase();
return idLower.contains(searchLower) ||
titleLower.contains(searchLower) ||
subTitleLower.contains(searchLower);
}).toList();
} else if (response.statusCode == 401) {
itemsList = [];
} else {
itemsList = [];
}
return itemsList;
} catch (e) {
if (kDebugMode) {
Logger().wtf(
"FetchItemsException $e \n\nResponseStatusCode ${statusCode!}");
}
rethrow;
}
}
The above code is when i am using a class of Item. The issues that i am having is i have switched to load and populate the data using List<HashMap<String, dynamic>> instead of Item class
The code above is working fine if i am using List but fails when i am using List<HashMap<String, dynamic>>
I am going to highlight the section that is failing. Below is how i was checking if the following variables idLower, titleLower, subTitleLower contains what is in the search query and return the Item. Below is the code of how i was doing that
if (response.statusCode == 200) {
itemsList = json
.decode(response.body)
.map<Item>((json) => Item.fromJson(json))
.where((item) {
final idLower = item.id.toLowerCase();
final titleLower = item.title.toLowerCase();
final subTitleLower = item.subTitle.toLowerCase();
final searchLower = query.toLowerCase();
return idLower.contains(searchLower) ||
titleLower.contains(searchLower) ||
subTitleLower.contains(searchLower);
}).toList();
}
Below is how i am fetching using List<HashMap<String, dynamic>>
static Future<List<HashMap<String, dynamic>>> fetchLists(
String url, String query) async {
try {
final response = await http.get(Uri.parse(url), headers: {
"Content-Type": "application/json",
"Authorization": "Bearer tltsp6dmnbif01jy9xfo9ssn4620u89xhuwcm5t3",
}).timeout(const Duration(seconds: Config.responseTimeOutInSeconds));
statusCode = response.statusCode;
final List<HashMap<String, dynamic>> responseList;
if (response.statusCode == 200) {
responseList = json
.decode(response.body)
.map<HashMap<String, dynamic>>(
(e) => HashMap<String, dynamic>.from(e))
.where((mapItem) {
final idLower = mapItem["id"].toLowerCase();
final titleLower = mapItem["title"].toLowerCase();
final subTitleLower = mapItem["subTitle"].subTitle.toLowerCase();
final searchLower = query.toLowerCase();
return idLower.contains(searchLower) ||
titleLower.contains(searchLower) ||
subTitleLower.contains(searchLower);
}).toList();
} else if (response.statusCode == 401) {
responseList = [];
} else {
responseList = [];
}
return responseList;
} catch (e) {
if (kDebugMode) {
Logger().wtf(
"FetchUsersUsingListOfStringObjectHashMapException $e \n\nResponseStatusCode ${statusCode!}");
}
rethrow;
}
}
And below is how i have tried to check if the items in the HashMap is contained in the query but its not working
if (response.statusCode == 200) {
responseList = json
.decode(response.body)
.map<HashMap<String, dynamic>>(
(e) => HashMap<String, dynamic>.from(e))
.where((mapItem) {
final idLower = mapItem["id"].toLowerCase();
final titleLower = mapItem["title"].toLowerCase();
final subTitleLower = mapItem["subTitle"].subTitle.toLowerCase();
final searchLower = query.toLowerCase();
return idLower.contains(searchLower) ||
titleLower.contains(searchLower) ||
subTitleLower.contains(searchLower);
}).toList();
}

Related

Retrieving data from http web call in flutter into a list object always empty

List is always empty even though body has contents. I am new to flutter so bare with me if this is basic. I am wanting to get back a list of station data I am coming from a c# background so forgive me if am missing something simple the test string body has the items and can see the items when i debug
class HttpService {
final String url = "url hidden";
final String host = 'url hidden';
final String apiSegment = "api/";
// ignore: non_constant_identifier_names
void login(email, password) async {
try {
Map<String, String> body = {
'username': email,
'password': password,
};
Map<String, String> headers = {'Content-Type': 'application/json'};
final msg = jsonEncode(body);
Response response =
await post(Uri.parse("$url/Login"), headers: headers, body: msg);
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data['jwtToken']);
print('Login successfully');
final prefs = await SharedPreferences.getInstance();
await prefs.setString('jwtToken', data['jwtToken']);
List<Stations> stationData = await getStationData('11');
var test = stationData;
} else {
print('failed');
}
} catch (e) {
print(e.toString());
}
}
Future<List<Stations>> getStationData(String stationId) async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('jwtToken');
const String path = 'Station/GetAllStationData';
final uri = Uri.parse('$url/api/$path')
.replace(queryParameters: {'stationId': stationId});
List<Stations> stationData = <Stations>[];
try {
Response res = await get(uri, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer $token',
});
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
var body2 = body.toString();
stationData = body
.map(
(dynamic item) => Stations.fromJson(item),
)
.toList();
} else {
throw "Unable to retrieve posts.";
}
} catch (e) {
print(e.toString());
}
return stationData;
}
}
I am calling my function from the same class
List<Stations> stationData = await getStationData('11');
Data from body
Actually the problem is you are returning the data after the end of try catch.
Try this
Future<List<Stations>> getStationData(String stationId) async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('jwtToken');
const String path = 'Station/GetAllStationData';
final uri = Uri.parse('$url/api/$path')
.replace(queryParameters: {'stationId': stationId});
try {
Response res = await get(uri, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer $token',
});
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
final stationData = List<Stations>.from(body.map((item) => Stations.fromJson(item))); // made some changes
return stationData;
} else {
throw "Unable to retrieve posts.";
}
} catch (e) {
rethrow;
}
}
I hope this will help you

Flutter: How to send multiple images using for loop

I am using http package to perform multipart request.I am trying to upload multiple images using for loop but I am not getting any idea how to do it following is my postman response in the below image you can see 2 fields one is attribute and another one is image here I want to loop only adhar and pan inside attributes after sending "mobileno":"4567654","role":"p","userstatus":"D", to database
following is my multipart request code
Future<void> insertCategory(String category, BuildContext context) async {
var flutterFunctions =
Provider.of<FlutterFunctions>(context, listen: false);
var data = {"mobileno":"4567654","role":"p","userstatus":"D","adhar":"adhar","pan":"pan"};
var url = PurohitApi().baseUrl + PurohitApi().insertcategory;
Map<String, String> obj = {"attributes": json.encode(data).toString()};
try {
loading();
final client = RetryClient(
http.Client(),
retries: 4,
when: (reponse) {
return reponse.statusCode == 401 ? true : false;
},
onRetry: (request, response, retryCount) async {
if (retryCount == 0 && response?.statusCode == 401) {
var accesstoken = await Provider.of<Auth>(context, listen: false)
.restoreAccessToken();
request.headers['Authorization'] = accesstoken;
print(accesstoken);
}
},
);
var response = await http.MultipartRequest('Post', Uri.parse(url))
..files.add(await http.MultipartFile.fromPath(
"imagefile", flutterFunctions.imageFile!.path,
contentType: MediaType("image", "jpg")))
..headers['Authorization'] = token!
..fields.addAll(obj);
final send = await client.send(response);
final res = await http.Response.fromStream(send);
var messages = json.decode(res.body);
loading();
print(messages);
} catch (e) {
print(e);
}
}
Future<Object> addUserImages(List<XFile> files, String userID, String token) async {
try {
var url = Uri.parse(API_BASE_URL + addUserImagesUrl);
var request = http.MultipartRequest("POST", url);
request.headers['Authorization'] = "Bearer ${StaticServices.userBaseModel!.token!.token}";
for (var i = 0; i < files.length; i++) {
String fileName = DateTime.now().microsecondsSinceEpoch.toString().characters.takeLast(7).toString();
var pic = http.MultipartFile.fromBytes("files", await File(files[i].path).readAsBytes(), filename: '${userID}_${i}_$fileName', contentType: MediaType("image", files[i].mimeType ?? "png"));
//add multipart to request
request.files.add(pic);
}
var response = await request.send();
var responseData = await response.stream.toBytes();
var responseString = String.fromCharCodes(responseData);
if (response.statusCode == 200) {
return Success(response: Images.fromJson(jsonDecode(responseString)));
}
return Failure(
errorMessage: responseString,
);
} on HttpException {
return Failure(errorMessage: "No Internet Connection");
} on FormatException {
return Failure(errorMessage: "Invalid Format");
} on SocketException {
return Failure(errorMessage: "No Internet Connection");
} catch (e) {
return Failure(errorMessage: "Invalid Error");
}
}

How can i add headers for authorization and content-type flutter

i have this code for to call api;
how can I add authorization and content-type headers to this?
final url = Uri.parse('https://api.collectapi.com/economy/hisseSenedi');
var counter;
var hisseResult;
Future callHisse() async {
try{
final response = await http.get(url);
if(response.statusCode == 200){
var result = hisselistFromJson(response.body);
if(mounted);
setState(() {
counter = result.data.length;
hisseResult = result;
});
return result;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
}
Thanks for your help
you can do this:
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': '<Your token>'
};
final response = await http.get(url,headers:requestHeaders);

Can't upload multiple image in flutter POST request

I'm trying to upload multiple images in backend.
I got this response when I'm trying to print files:
[Instance of 'MultipartFile', Instance of 'MultipartFile', Instance of 'MultipartFile']
but at a server side I got null array {}. This is my method. I'm using http for api communication.
Future<Map<String, dynamic>> postWithMultiImage(
String _url,
Map<String, String> _headers,
Map<String, String> _params,
String _imageKey,
List _imageFile) async {
if (_headers != null) {
print('_headers => $_headers');
}
print('_params => $_params');
print('_url => $_url');
var request = http.MultipartRequest("POST", Uri.parse(BASE_URL + _url));
if (_headers != null) {
request.headers.addAll(_headers);
}
if (_params != null) {
request.fields.addAll(_params);
}
if (_imageFile != null) {
for (int i = 0; i < _imageFile.length; i++) {
final _type = lookupMimeType(_imageFile[i]);
final _name =
'${DateTime.now().toIso8601String()}.${_type.split('/').last}';
final _partFile = http.MultipartFile(
_imageKey,
File(_imageFile[i]).openRead(),
File(_imageFile[i]).lengthSync(),
filename: _name);
request.files.add(_partFile);
}
print('request files: ${request.files}');
}
var response = await request.send();
final code = response.statusCode;
print('response code => $code');
final responseBody = await http.Response.fromStream(response);
final body = responseBody.body;
final jsonBody = json.decode(body);
Map<String, dynamic> _resDic;
if (code == 200) {
_resDic = Map<String, dynamic>.from(jsonBody);
_resDic[STATUS] = _resDic[SUCCESS] == 1;
} else {
_resDic = Map<String, dynamic>();
_resDic[STATUS] = false;
_resDic[IS_TOKEN_EXPIRED] = 0;
_resDic[MESSAGE] = jsonBody[MESSAGE] != null
? jsonBody[MESSAGE]
: 'Something went wrong';
}
_resDic[HTTP_CODE] = code;
return _resDic;
}
Thanks in advance.
You can try >>THIS<<

Flutter & Firebase - Get a specific field from document

I have been trying to get a specific field from a specific document. I need token for toWho. But I always got null. How do I fix this?
Main Code is
Future<String> getUserToken(String toWho) async {
DocumentSnapshot _doc = await FirebaseFirestore.instance.doc("tokens/" + toWho).get();
if (_doc != null) {
Map<String, dynamic> _data = _doc.data();
return _data["token"];
} else {
return null;
}
}
in Repository
Future<bool> sendMessage(
MessageModel sendingMessage, UserModel currentUser) async {
if (appMode == AppMode.DEBUG) {
return true;
} else {
var _writePrcs = await _firestoreDBService.saveMessage(sendingMessage);
if (_writePrcs) {
var _token = "";
if (_userToken.containsKey(sendingMessage.toWho)) {
_token = _userToken[sendingMessage.toWho];
print("Token lokalden geldi.");
} else {
_token = await _firestoreDBService.getUserToken(sendingMessage.toWho);
_userToken[sendingMessage.toWho] = _token;
print("Token veritabanından geldi.");
}
Thanks for your help from now on
Try ...........
Future<String> getUserToken(String toWho) async {
DocumentSnapshot _doc = await
FirebaseFirestore.instance.collection("tokens/groupChatId/message").doc(toWho).get();
if (_doc != null) {
Map<String, dynamic> _data = _doc.data();
return _data["token"];
} else {
return null;
}
}