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

标签 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

最佳答案

您需要在从Firestore获取数据之前添加 await ,因为它是异步的,并且您不等待结果并返回已初始化为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)正在打印,但不会返回,因为在异步执行完成之前调用了return。

关于firebase - 返回Firebase Flutter中的集合数时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59291240/

相关文章:

ios - 添加 Firebase CocoaPods 后无法构建项目

android - RecyclerView 延迟显示其项目

Flutter TextFormField 文本在溢出时隐藏

flutter - 如何将容器垂直拉伸(stretch)到最大屏幕?

flutter - 如何将列表/映射初始化为默认参数?

flutter - 如何在 Dart 代码下方添加抽屉导航和银色 AppBar?

swift - 错误的 dispatch 组通知安置?

javascript - 在模式 : 'history' vue router doesn't work 之后

Flutter MediaQuery.of(context).size.width 值与实际屏幕分辨率不同

dart - 我将如何偏移 24 小时时间范围以从当前时间开始并在 24 小时后结束