Issues with flutter futures - map results in List<Future> - flutter

I'm having issues with the return type of this HTTP request, I need to return Future<List> but the map is returning a List<Future>. I don't know how to get the CustomerInfo without it being a future and I don't know how to return it any other way.
if (response.statusCode == 200) {
Iterable l = json.decode(response.body);
final data = List.from(l.map((model) async {
final name = model['UserName'];
final id = model['UserICode'];
return {name, id};
}));
final users = data.map<CustomerInfo>((e) async {return await getFaxinfo(e.id, e.name);});
return users;
} else {
throw 'err';
}
}
Future<CustomerInfo> getFaxinfo(
String id,
String name,
) async {
final baseUrl = 'localhost';
final int port = 3003;
final accountsPath = '/accounts';
final accountsFaxInfoPath = '$accountsPath/fax-info';
final Map<String, dynamic> queryParam = {'id': id};
final uri = Uri(
scheme: 'http',
path: accountsFaxInfoPath,
host: baseUrl,
queryParameters: queryParam);
final response = await http.get(uri);
return CustomerInfo(sent: 200, received: 300, name: 'Test');
}

The problem is that an async function always returns a Future no matter if you call await inside it or not. To fix it a good approach is to use list comprehension. A simple for loop also would do.
Instead of those 2 maps that result in List<Future>:
final data = List.from(l.map((model) async {
final name = model['UserName'];
final id = model['UserICode'];
return {name, id};
}));
final users = data.map<CustomerInfo>((e) async {return await getFaxinfo(e.id, e.name);});
Do the following with list comprehension:
final users = [
for (final model in l)
await getFaxinfo(model['UserICode'], model['UserName'])
];
Now if you want to make the HTTP calls in parallel it's possible to do a Future.wait() in a List<Future> to get the result as List<CustomerInfo>. Something like the following:
final users = await Future.wait(l.map((model) async =>
await getFaxinfo(model['UserICode'], model['UserName'])));

Related

flutter http get request with parameters

I want to send a GET http request with parameters, my problem is that when I add the parameters in the request URL manually it works fine, but when I pass them as parameters it returns an exception without any explanation and somehow the execution stops after Uri.https
here is the code that I want to achieve
Future<List<LawFirm>> getLawFirms () async {
Map<String, dynamic> parameters = {
'total': true
};
final uri =
Uri.http('www.vision.thefuturevision.com:5000',
'/api/law-firm', parameters);
final response = await http.get(uri);
var dynamicResponse = jsonDecode(response.body);
totaLawFirms = await dynamicResponse['total'];
var lawFirms = await dynamicResponse['data'];
List<LawFirm> list = List<LawFirm>.from(lawFirms.map((x) => LawFirm.fromJson(x)));
print(list);
notifyListeners();
return list;
}
and here is the manual way which shouldn't be applied
final response = await get(Uri.parse('$baseURL/law-firm?total=true'));
I have also tried the dio library from pub.dev but also wasn't helpful.
And finally thanks in advance to everyone
You may try this
Map<String, dynamic> parameters = {
'total': true
};
var uri = Uri(
scheme: 'http',
host: 'www.vision.thefuturevision.com:5000',
path: '/law-firm',
queryParameters: parameters,
);
final response = await http.get(uri);
import 'package:http/http.dart' as http;
final response =
await http.get(Uri.parse("${Constants.baseUrl}endpoint/param1/param2"));
Just modify your GET request like this.
Try this
import 'package:http/http.dart' as http;
callAPI() async {
String login = "sunrule";
String pwd = "api";
Uri url = Uri.parse(
"http://vijayhomeservices.in/app/api/index.php?apicall=login&login=$login&password=$pwd");
final response = await http.get(url);
if (response.statusCode == 200) {
final body = json.decode(response.body);
print(body.toString());
} else {
throw Exception("Server Error !");
}
}
Query parameters don't support bool type. Use String instead: 'true'.
A value in the map must be either a string, or an Iterable of strings, where the latter corresponds to multiple values for the same key.
Map<String, dynamic> parameters = {'total': 'true'};
final uri = Uri.http(
'www.vision.thefuturevision.com:5000', '/api/law-firm', parameters);
print(uri); // http://www.vision.thefuturevision.com:5000/api/law-firm?total=true
See Uri constructor for details.

An optimize way for tryAutoLogin function in flutter?

I want to create a function for auto login like Facebook in flutter but don't know the best way to do it.
My function for login and auto login, I used SharedPreferences plugin for store data.
SignIn function:
Future<void> signIn(String userName, String pass) async {
final url = Uri.parse('MyAPI_login');// sorry it for privacy
debugPrint("$userName / $pass");
try {
var respone = await http.post(url, body: {
'user_name': userName,
'password': pass,
'platform': 'mobile',
'device_token': '',
});
final reponseData = jsonDecode(respone.body);
_userName = userName;
_token = reponseData['data']['accessToken'];
_expiryDate = DateTime.now().add(Duration(
seconds: int.parse(reponseData['data']['tokenExpireAt'].toString())));
_refreshToken = reponseData['data']['refreshToken'].toString();
_timerRefreshToken =
int.parse(reponseData['data']['refreshTokenExpireAt'].toString());
// debugPrint(
// '$_token \n $_expiryDate \n $_refreshToken \n $_timerRefreshToken');
notifyListeners();
final prefs = await SharedPreferences.getInstance();
final userData = json.encode({
'_userId': _userName.toString(),
'token': _token.toString(),
'expiryDate': _expiryDate!.toIso8601String(),
'refreshToken': _refreshToken,
'timerRefreshToken': _timerRefreshToken.toString(),
});
await prefs.setString('userData', userData);
} catch (error) {
throw Exception(error.toString());
}}
TryAutoLogin function:
Future<bool> tryAutoLogin() async {
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('userData')) {
return false;
}
final extractedUserData = json
.decode(prefs.getString('userData').toString()) as Map<String, dynamic>;
final expiryDate =
DateTime.parse(extractedUserData['expiryDate'].toString());
if (expiryDate.isBefore(DateTime.now())) {
_token = extractedUserData['refreshToken'].toString();
_expiryDate = DateTime.now().add(
Duration(seconds: int.parse(extractedUserData['timerRefreshToken'])));
_refreshNewToken(extractedUserData['refreshToken'].toString());
}
return true;}
RefreshNewToken function:
Future<void> _refreshNewToken(String oldRefreshToken) async {
final url =
Uri.parse('MyAPI_refreshtoken');
var respone = await http.post(url, body: {'refreshToken': oldRefreshToken});
debugPrint(respone.body);}
My API for login response is like this:
{"data":{"tokenKey":"Authorization","tokenType":"Bearer","accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1YzkyMTQwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTMsImV4cCI6MTY1ODI4NTk5M30.3kMByfweUhzQM-4d5S0G7tUaC0e-nZLJF3_dbdV_7fM","tokenExpireAt":1658285940964,"refreshToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1YzkyMTQwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTMsImV4cCI6MTY1ODM2ODc5M30.Bv7PZrnx9zDzwIuxNMppFxlwZlJEnthVjEYBKYl-aWM","refreshTokenExpireAt":1658368740964},"message":"Logged in successfully!","status":200,"errors":null}
Also, my API has a refresh token request, it returns like this:
{"data":{"tokenKey":"Authorization","tokenType":"Bearer","accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1ZjQyOGUwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTQsImV4cCI6MTY1ODI4NTk5NH0.wcyouoprMHFnRD4_oSpP9RSasxMBrktX6nZI2x2PQec","tokenExpireAt":1658285940242,"refreshToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1ZjQyOGUwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTQsImV4cCI6MTY1ODM2ODc5NH0.y-8MP4M_1LzCwmqo_KQZGyQXkycrxdOLWz_fdqIPRyQ","refreshTokenExpireAt":1658368740242},"message":"Request successfully!","status":200,"errors":null}

Problem with filling the list after await command

I have just started Flutter and I am stuck at a point. Below is some part of my function that first uploads provided pictures on firebase storage and then get their downloadable URLs and store them in the list of string. It should upload data to firestore with the list of URLs obtained from command list.add(imageUrl);
List<String> list = [];
imgList.forEach((element) async {
final String filePath = element.path;
final res =
filePath.substring(filePath.lastIndexOf('im'), filePath.length);
final ref = FirebaseStorage.instance.ref().child('images').child(res);
await ref.putFile(File(element.path));
final imageUrl = await ref.getDownloadURL();
list.add(imageUrl);
});
final doc = FirebaseFirestore.instance.collection('cars').doc();
but it doesn't happens because the following line is called before filling the list due to await.
await doc.set({
'id': doc,
'img': list,
'price': 14450,
'make': 'Toyota',
'year': 2015`
});
Add await before imgList.forEach like
List<String> list = [];
await imgList.forEach((element) async {
final String filePath = element.path;
final res =
filePath.substring(filePath.lastIndexOf('im'), filePath.length);
final ref = FirebaseStorage.instance.ref().child('images').child(res);
await ref.putFile(File(element.path));
final imageUrl = await ref.getDownloadURL();
list.add(imageUrl);
});
final doc = FirebaseFirestore.instance.collection('cars').doc();
edit
if this doesn't work then you may use for loop instead of forEach like
List<String> list = [];
for(var element in imgList) {
final String filePath = element.path;
final res =
filePath.substring(filePath.lastIndexOf('im'), filePath.length);
final ref = FirebaseStorage.instance.ref().child('images').child(res);
await ref.putFile(File(element.path));
final imageUrl = await ref.getDownloadURL();
list.add(imageUrl);
}
final doc = FirebaseFirestore.instance.collection('cars').doc();

Function call not working after migrating to null safe flutter

I have defined a function to get some information from the server
#override
Future<HttpResponse<dynamic>> getAppInfo() async {
const _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{};
final _data = <String, dynamic>{};
final _result = await _dio.fetch(_setStreamType<HttpResponse<dynamic>>(
Options(method: 'GET', headers: <String, dynamic>{}, extra: _extra)
.compose(_dio.options, '/user/app-info',
queryParameters: queryParameters, data: _data)
.copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl)));
final value = _result.data;
final httpResponse = HttpResponse(value, _result);
return httpResponse;
}
I am passing this function as an argument at run time to different function. Another function is defined this way
Future<HttpResponse?> handleApi(
Function function, [
List<dynamic>? args,
]) async {
try {
final HttpResponse httpResult = await Function.apply(
function,
args,
) as HttpResponse; // This following bloc of code is not getting called
if (httpResult.response.statusCode == HttpStatus.ok ||
httpResult.response.statusCode == HttpStatus.created) {
return httpResult;
}
} on Exception catch (e) {
return null;
}
}
And i am passing first function to second function as an argument. It was working fine without null safe version of flutter. And after the migration to null safe, the call is not happening on the function at run time.
I am calling handleApi fucntion following way
final httpResultOrError = await _apiCallHandler.handleApi(
getAppInfo,
);

Question mark converted to %3F in URI

I'm working on a project and I'm trying to get information from an API. When I write the link it doesn't detect the character "?" and it substitutes this char for "%3F" so I can't access to the API.
final String _charactersUrl = '/api/character/?page=2';
I get status code 500 from the API:
https://rickandmortyapi.com/api/character/%3Fpage=3
The class that gets information from the API
class Api {
final String _baseUrl = 'rickandmortyapi.com';
final String _charactersUrl = '/api/character/?page=2';
final String _charactersJsonKey = 'results';
final HttpClient _httpClient = HttpClient();
Future<List<Character>> getCharacters() async {
final uri = Uri.https(_baseUrl, _charactersUrl);
final response = await _getJson(uri);
if (response == null || response[_charactersJsonKey] == null) {
print('Api.getCharacters(): Error while retrieving characters');
return null;
}
return _convert(response[_charactersJsonKey]);
}
Future<Map<String, dynamic>> _getJson(Uri uri) async {
try {
final request = await _httpClient.getUrl(uri);
final response = await request.close();
if (response.statusCode != HttpStatus.OK) {
print('Api._getJson($uri) status code is ${response.statusCode}');
return null;
}
final responseBody = await response.transform(utf8.decoder).join();
return json.decode(responseBody);
} on Exception catch (e) {
print('Api._getJson($uri) exception thrown: $e');
return null;
}
}
List<Character> _convert(List charactersJson) {
List<Character> characters = <Character>[];
charactersJson.forEach((character) {
characters.add(Character.fromJson(character));
});
return characters;
}
}
I would be very grateful if someone could help me. Thanks!
The Uri class expects you to use the Uri.https constructor differently.
The third positional parameter is queryParameters, which you should use instead of passing your query parameters to the unencodedPath:
final String _baseUrl = 'rickandmortyapi.com';
final String _charactersPath = '/api/character/';
final Map<String, String> _queryParameters = <String, String>{
'page': '2',
};
Future<List<Character>> getCharacters() async {
final uri = Uri.https(_baseUrl, _charactersPath, _queryParameters);
...