T233
T233

Reputation: 23

ADD method in List does not work(List.add()) in flutter

code

Future<List<String>> getdetails() async {
    List<String> details;

    String user = await Auth.getcurrent(); //FirebaseUser()
    DocumentReference ref = Firestore.instance.collection('users').document(
        '$user');
    DocumentSnapshot s = await ref.get();
    print(s.data['email']);    //This works
    details.add(s.data['email']);   //statements after this don't get printed
    print("bb");  
    print(details);  
    return details;
  }

The output for this is: only s.data['email'] gets printed out

print(s.data['email']); works fine BUT details.add(s.data['email']); doesnt work and statements after this don't get printed.

To test this,after rearranging the statements,print statements after details.add() still do not work

 Future<List<String>> getdetails() async {
    List<String> details;

    String user = await Auth.getcurrent(); //FirebaseUser()
    DocumentReference ref = Firestore.instance.collection('users').document(
        '$user');
    DocumentSnapshot s = await ref.get();
    print(s.data['email']);  //This works
    print("bb");                    //This works
    details.add(s.data['email']);      //statements after this don't get printed
    print("cc")   //This doesn't get printed
    print(details);  //This doesn't get printed
    return details;
  } 

Output for this: 2 print statements get printed now instead of 1

Upvotes: 2

Views: 3201

Answers (2)

konkri
konkri

Reputation: 235

I had a similar problem but with the List<T>.empty(). It turns out that there is an optional parameter growable set to false by default. I set it to true and it works fine.

Upvotes: 1

Milvintsiss
Milvintsiss

Reputation: 1460

It's because you didn't instantiate your List and you invoke .add method on a null List. Try

List<String> details = [];

instead of

List<String> details;

Upvotes: 2

Related Questions