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) {
    print(userSearchItems.length); // result 1 and it will be executed after 2 seconds 

  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 {

    .listen((data) =>

      User user = new User.fromDocument(doc);
      UserSearchItem searchItem = new UserSearchItem(user);

      return 'success';

void yourFunction() async{
   await submitAll();

Then call yourFunction().