如何获取作为Future <string>的Firestore.instance.collection()?

时间:2019-04-25 02:32:18

标签: firebase dart flutter

我正在尝试使用Firestore.instance.collection(currentUser)从我的Firebase中获取一些数据,但是currentUser是Future。如何实现此目的?

我有以下

class FoodCart extends StatefulWidget {
  @override
  _FoodCartState createState() => _FoodCartState();
}

class _FoodCartState extends State<FoodCart> {

  @override
  Widget build(BuildContext context) {

    String currentUser;
    firebaseHelper().getCurrentUser().then((result){
      currentUser = result;
    });

    return Scaffold(
      appBar: AppBar(
        title: Text("FoodCart"),
        backgroundColor: Colors.lightBlue,
      ),
      body: StreamBuilder<QuerySnapshot>(//recover data from firebase and shows in the listview
        stream: Firestore.instance.collection(currentUser).snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError)
            return new Text('Error: ${snapshot.error}');
          switch (snapshot.connectionState) {
            case ConnectionState.waiting: return new Text('Loading...');
            default:
              return new ListView(
                children: snapshot.data.documents.map((DocumentSnapshot document) {
                  return foodCard(document['name'],document['description']);
                }).toList(),
              );
          }
        },
      ),
    );
  }
}

在我的firebaseHelper()中,我有:

...
    Future<String> getCurrentUser() async{
      FirebaseUser user = await FirebaseAuth.instance.currentUser();
      if(user != null){//if exists a current user, then
        return user.uid;
      }else{
        return null;
      }
    }
...

但是在流中:Firestore.instance.collection(currentUser).snapshots(), currentUser始终返回null,因为currentUser = result归于Future函数(然后)中。换句话说,我需要在需要String函数的字段中使用Future函数的结果。

2 个答案:

答案 0 :(得分:0)

呼叫类似

firebaseHelper().getCurrentUser().then((result){
  setState(() {
    currentUser = result;
  })
});

答案 1 :(得分:0)

您可以做的是重新渲染视图,这是使用功能setState ({});

完成的
class FoodCart extends StatefulWidget {
  @override
  _FoodCartState createState() => _FoodCartState();
}

class _FoodCartState extends State<FoodCart> {
// global variable
String currentUser;

// -------------- create this method to get the current user
 Future<Null> _getCurrentUser() async {
    var result = await firebaseHelper().getCurrentUser();

//we notified that there was a change and that the UI should be rendered
    setState(() {
      currentUser = result;
    });
  }
 // Add this method
  Widget buildBody() {
    if (this.currentUser == null) {
      return Container();
    } else {
      return StreamBuilder<QuerySnapshot>(//recover data from firebase and shows in the listview
        stream: Firestore.instance.collection(currentUser).snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError)
            return new Text('Error: ${snapshot.error}');
          switch (snapshot.connectionState) {
            case ConnectionState.waiting: return new Text('Loading...');
            default:
              return new ListView(
                children: snapshot.data.documents.map((DocumentSnapshot document) {
                  return foodCard(document['name'],document['description']);
                }).toList(),
              );
          }
        },
      );
    }
  }

// ------------ add this method
@override
  void initState() {
    this._getCurrentUser();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text("FoodCart"),
        backgroundColor: Colors.lightBlue,
      ),
      body: this.buildBody(),
    );
  }
}