如何获取Future的Firestore.instance.collection() ?

问题描述 投票:0回答:2

我正在尝试使用Firestore.instance.collection(currentUser)从我的Firebase获取一些数据,但currentUser是Future.How我可以完成这个吗?

我有以下内容

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

但是在stream:Firestore.instance.collection(currentUser).snapshots()中,currentUser总是返回null,因为currentUser = result被归入Future函数(然后)。换句话说,我需要使用结果在需要String函数的字段内的Future函数。如何实现这一目标?

firebase dart flutter
2个回答
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(),
    );
  }
}

0
投票

打电话给像

firebaseHelper().getCurrentUser().then((result){
  setState(() {
    currentUser = result;
  })
});
© www.soinside.com 2019 - 2024. All rights reserved.