列表中的ADD方法在抖动中不起作用(List.add())

时间:2020-04-14 10:14:20

标签: 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;
  }

此输出为: only s.data['email'] gets printed out

print(s.data['email']);可以正常工作,但details.add(s.data['email']);不起作用,并且此后的声明也无法打印。

要对此进行测试,请在重新排列语句之后,在details.add()之后打印语句仍然不起作用

 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;
  } 

此输出:2 print statements get printed now instead of 1

2 个答案:

答案 0 :(得分:0)

这是因为您没有实例化List,而是在空List上调用.add方法。 试试

List<String> details = [];

代替

List<String> details;

答案 1 :(得分:0)

我遇到了类似的问题,但是 List<T>.empty()。事实证明,默认情况下有一个可选参数 growable 设置为 false。我将它设置为 true,它工作正常。