I have a list of Followers (Model class) and it contains documentId for each user and using this documentId i am able to fetch InstaUser (again a model class) from the server using the API . The thing I want to do here is create a list of InstaUser and return it. Inside the forEach loop i am inserting elememts to the list variable but after the exection of loop the list still remains empty. Sharing the function snippet below , Can anyone please help me find the issue.
Future<List<InstaUser>> getMyFollowers() async {
List<InstaUser> list = [];
followerList.forEach((element) async {
// followerList contains documentId
String apiUrlForUsers =
constants().fetchapiUrl + 'details/${element.documentId}.json';
final currentFollowerResponse = await http.get(Uri.parse(apiUrlForUsers));
final currentFollowerData =
json.decode(currentFollowerResponse.body) as Map<String, dynamic>;
list.add(InstaUser(
dp: currentFollowerData['dp'],
userName: currentFollowerData['userName'],
website: currentFollowerData['website'],
bio: currentFollowerData['bio'],
title: currentFollowerData['title'],
email: currentFollowerData['email'],
keyIdFromServer: currentFollowerData['keyIdFromServer'],
uid: currentFollowerData['uid'],
));
print(
'Current length = ${list.length.toString()} ${currentFollowerData['title']}');
});
print('length = ${list.length}');
return list;}
Log report:-
Performing hot reload...
Syncing files to device sdk gphone x86...
Reloaded 10 of 1120 libraries in 738ms.
I/flutter (19300): length = 0
I/flutter (19300): Current length = 1 Uzumaki Narutoenter code here
I/flutter (19300): Current length = 2 Uchiha Sasuke
I am also not getting why its printing the length before any other print statements.