返回Firebase Flutter中的集合数时出错?

时间:2019-12-11 17:36:05

标签: firebase flutter dart google-cloud-firestore

我正在开发一个管理应用程序,因为我厌倦了从firebase返回用户数量,我从stackoverflow那里得到的帮助很少,并且能够在终端上打印,但是在应用程序上返回null可以有人帮助吗我。这是我的代码

    class _AdminState extends State<Admin> {



  Future<String> getUsersCount() async{
    var length = -1;
    await Firestore.instance.collection('users').getDocuments().then((myDocuments){
      print("${myDocuments.documents.length}");
      length = myDocuments.documents.length;
    });
    return Future.value(length.toString());
  }




  Page _selectedPage = Page.dashboard;
  MaterialColor active = Colors.indigo;
  MaterialColor notActive = Colors.grey;
  final databaseReference = Firestore.instance;



  bool isDelete= true;
  var values;

  TextEditingController categoryController = TextEditingController();
  TextEditingController brandController = TextEditingController();
  GlobalKey<FormState> _categoryFormKey = GlobalKey();
//GlobalKey<FormState> _brandFormKey = GlobalKey();
// BrandService _brandService = BrandService();
  CategoryService _categoryService = CategoryService();





  @override
  Widget build(BuildContext context) {

    return Scaffold(

        appBar: AppBar(
          title: Row(
            children: <Widget>[
              Expanded(
                  child: FlatButton.icon(
                      onPressed: () {
                        setState(() => _selectedPage = Page.dashboard);
                      },
                      icon: Icon(
                        Icons.dashboard,
                        color: _selectedPage == Page.dashboard
                            ? active
                            : notActive,
                      ),
                      label: Text('Dashboard'))),
              Expanded(
                  child: FlatButton.icon(
                      onPressed: () {
                        setState(() => _selectedPage = Page.manage);
                      },
                      icon: Icon(
                        Icons.sort,
                        color:
                        _selectedPage == Page.manage ? active : notActive,
                      ),
                      label: Text('Manage'))),
            ],
          ),
          elevation: 0.0,
          backgroundColor: Colors.white,
        ),
        body: _loadScreen());
  }



  Widget _loadScreen() {
    switch (_selectedPage) {
      case Page.dashboard:

        return FutureBuilder(
            future: getUsersCount(),
            builder: (BuildContext context, AsyncSnapshot<String> text) {
              print(text);
              if(text== "-1"){
              return CircularProgressIndicator();
              } else {
                return Column(
                  children: <Widget>[
                    ListTile(
                      subtitle: Text('Admin View', textAlign: TextAlign.center,
                        style: TextStyle(fontSize: 29.0,
                            color: Colors.indigo,
                            fontWeight: FontWeight.bold),),
                    ),
                    Expanded(child: GridView(
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,),
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.all(18.0), child: Card(
                          child: ListTile(title: FlatButton.icon(
                              onPressed: null,
                              icon: Icon(
                                Icons.directions_boat, color: Colors.black,),
                              label: Text("Boats", style: TextStyle(
                                  fontSize: 9, color: Colors.indigo),)),
                              subtitle: Text('3', textAlign: TextAlign.center,
                                style: TextStyle(
                                    color: active, fontSize: 50.0),)),
                        ),
                        ),
                        Padding(padding: const EdgeInsets.all(18.0),
                          child: Card(child: ListTile(
                              title: FlatButton.icon(
                                  onPressed: null,
                                  icon: Icon(
                                    Icons.people, color: Colors.black,),
                                  label: Text("Users", style: TextStyle(
                                      fontSize: 9, color: Colors.indigo),)),
                              subtitle: Text(text.data != null ? text.data : '',
                                textAlign: TextAlign.center,
                                style: TextStyle(color: active, fontSize: 50.0),
                              )),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(22.0),
                          child: Card(
                            child: ListTile(
                                title: FlatButton.icon(
                                    onPressed: null,
                                    icon: Icon(
                                      Icons.bookmark, color: Colors.black,),
                                    label: Text("Bookings", style: TextStyle(
                                        fontSize: 8, color: Colors.indigo),)),
                                subtitle: Text(
                                  '120',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      color: active, fontSize: 50.0),
                                )),
                          ),
                        ),
                      ],

                    ),

                    ),
                  ],
                );
              } })

我返回的是空字符串值,但是当包含这组行Text(text.data ??'default value')时,我能够清除该错误,但仍然无法清除我的问题,请有人帮助我 enter image description here

2 个答案:

答案 0 :(得分:2)

您需要先添加 await ,然后再从Firestore中获取数据,因为它是异步的,并且您无需等待结果并返回初始化为0的值

    Future<String> getUsersCount() async {
        var length = 0;
        await Firestore.instance.collection('users').getDocuments().then((myDocuments){
          print("${myDocuments.documents.length}");
          length = myDocuments.documents.length;
        });
        return Future.value(length.toString());
    }

您可以看到用户的值count(36)正在打印,但不会返回,因为在异步执行完成之前将调用返回。

答案 1 :(得分:0)

先通过getUsersCount方法初始化length to -1,然后在build method中初始化cloumn widget,然后再返回if (text == "-1"){ return Center( child: CircularProgressIndicator(backgroundColor: Colors.red,) ); } else{ return Column(....) } 检查文本(快照值):

    fetch("http://localhost:3000/").then(response => {
        console.log(response);
    }).catch(error => {
        console.log(error);
    }).then(window.location.reload(false));