Flutter add item to list

I will try to give an explanation of what is happing here take a look on this code:

import 'dart:async';

void main() {
  List<int> userSearchItems = [];

  Timer _sendTimeOutTimer;

  const oneSec = Duration(seconds: 2);
  _sendTimeOutTimer = Timer.periodic(oneSec, (Timer t) {
    userSearchItems.add(1);
    print(userSearchItems.length); // result 1 and it will be executed after 2 seconds 
    _sendTimeOutTimer.cancel();
  });

  print(userSearchItems.length); // result 0 and it will be executed first
}

The print inside asynchronous action(Timer) it will be executed after 2 seconds means after the asynchronous action ends but the one which is outside of asynchronous action(Timer) it will be executed directly without waiting 2 seconds, in your case the asynchronous action is listening to data .listen((data) =>, so if you print the length outside of your asynchronous action you will not see the deferent because the item is not added yet.

Solution: you can create function witch return Future and then wait until it's finished then print the length.

List<UserSearchItem> userSearchItems = [];

Future<String> submitAll() async {

Firestore.instance
    .collection('insta_users')
    .snapshots()
    .listen((data) =>
    data.documents.forEach((doc){
      print(data.documents.length);

      User user = new User.fromDocument(doc);
      UserSearchItem searchItem = new UserSearchItem(user);
      userSearchItems.add(searchItem);
      print(user.bio);

      return 'success';
    }));
}

void yourFunction() async{
   await submitAll();
   print("Loaded");
   print(userSearchItems.length);
}

Then call yourFunction().