我想从Future中获取一个整数值,在flutter和firestore中打印Instance of Future'动态'函数

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

我想在Future函数中得到一个整数值,当我按下fab按钮时,必须在if条件下进行比较,而不是在日志控制台“未来实例”中给出的集合中的文档数量,但是我需要我的方法来返回一个数字。这是我的代码:

class MembresPage extends StatefulWidget {
  @override
  _MembresPageState createState() => _MembresPageState();
}

class _MembresPageState extends State<MembresPage> {
  Map<String, String> sublingData = {};
  String nomComplet;
  String adresse;
  String ldNais;
  QuerySnapshot subling;

  CrudMethods crudObj = new CrudMethods();

  Future<bool> addDialog(BuildContext context) async{
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context){
          return AlertDialog(
            title: Text('Ajouter Membre', style: TextStyle(fontSize: 15.0)),
            content: Column(
              children: <Widget>[
                TextField(
                  decoration: InputDecoration(hintText: 'Nom Complet'),
                  onChanged: (value){
                    this.nomComplet =value;
                  },
                ),
                SizedBox(height: 8.0),
                TextField(
                  decoration: InputDecoration(hintText: 'Ex: Kinshasa, le 21/12/1960'),
                  onChanged: (value){
                    this.ldNais = value;
                  },
                ),
                SizedBox(height: 8.0),
                TextField(
                  decoration: InputDecoration(hintText: 'Adresse'),
                  onChanged: (value){
                    this.adresse = value;
                  },
                ),
              ],
            ),
            actions: <Widget>[
              FlatButton(
                child: Text('Ajouter'),
                textColor: Colors.deepOrangeAccent[400],
                onPressed: () async {
                    Navigator.of(context).pop();
                    sublingData = {
                      'nomComplet':this.nomComplet,
                      'ldNais': this.ldNais,
                      'adresse':this.adresse
                    };
                    PaiementStripe().addMembers(sublingData).then((result){
                      dialogTrigger(context);
                    }).catchError((e){
                      print(e);
                    });
                },
              )
            ],
          );
        });
  }
  Future<bool> updateDialog(BuildContext context, selectedDoc) async{
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context){
          return AlertDialog(
            title: Text('Modifier Membre', style: TextStyle(fontSize: 15.0)),
            content: Column(
              children: <Widget>[
                TextField(
                  decoration: InputDecoration(hintText: 'Nom Complet'),
                  onChanged: (value){
                    this.nomComplet =value;
                  },
                ),
                SizedBox(height: 8.0),
                TextField(
                  decoration: InputDecoration(hintText: 'Ex: Kinshasa, le 21/12/1960'),
                  onChanged: (value){
                    this.ldNais = value;
                  },
                ),
                SizedBox(height: 8.0),
                TextField(
                  decoration: InputDecoration(hintText: 'Adresse'),
                  onChanged: (value){
                    this.adresse = value;
                  },
                ),
              ],
            ),
            actions: <Widget>[
              FlatButton(
                child: Text('Modifier'),
                textColor: Colors.deepOrangeAccent[400],
                onPressed: (){
                  Navigator.of(context).pop();
                  /*sublingData = {
                    'nomComplet':this.nomSubling,
                    'lieuNais': this.lieuNais,
                    'dateNais':this.dateNais
                  };*/
                  PaiementStripe().updateMembers(selectedDoc,{
                    'nomComplet':this.nomComplet,
                    'ldNais': this.ldNais,
                    'adresse':this.adresse
                  }).then((result){
                    //dialogTrigger(context);
                  }).catchError((e){
                    print(e);
                  });
                  PaiementStripe().getMembers().then((result){
                    setState(() {
                      subling = result;
                    });
                  });
                },
              )
            ],
          );
        });
  }

  Future<bool> dialogTrigger(BuildContext context) async{
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context){
          return AlertDialog(
            title: Text('Info', style: TextStyle(fontSize: 15.0)),
            content: Text('Membre ajouté'),
            actions: <Widget>[
              FlatButton(
                child: Text('OK'),
                textColor: Colors.deepOrangeAccent[400],
                onPressed: (){
                  PaiementStripe().getMembers().then((result){
                    setState(() {
                      subling = result;
                    });
                  });
                  Navigator.of(context, rootNavigator: true).pop();
                },
              )
            ],
          );
        });
  }

  void showSnackBar(BuildContext context, docID){
    var snackBar = SnackBar(
        content: Text("Voulez vous Supprimer le membre?"),
      action: SnackBarAction(
          label: "OUI",
          onPressed: (){
            PaiementStripe().deleteMembers(docID);
            PaiementStripe().getMembers().then((result){
              setState(() {
                subling = result;
              });
            });
          }
      ),
    );
    Scaffold.of(context).showSnackBar(snackBar);
  }

  void seeSnackBar(BuildContext context){
    var snackBar = SnackBar(
      content: Text("Vous avez le maximum de membres"),
    );
    Scaffold.of(context).showSnackBar(snackBar);
  }

  @override
  void initState(){
    PaiementStripe().getMembers().then((result){
      setState(() {
        subling = result;
      });
    });
    super.initState();
  }

// the method that I need to return an Integer value

Future<int> countDocuments() async {
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    QuerySnapshot _myDoc = await Firestore.instance.collection('users').document(user.uid).collection('sublings').getDocuments();
    List<DocumentSnapshot> _myDocCount = _myDoc.documents;
    return _myDocCount.length;
    //Count of Documents in Collection
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton:Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            FloatingActionButton(
              heroTag: 'fab1',
              onPressed: (){
//the test comparison
                  if (countDocuments() < 5){
                    addDialog(context);
                    print(countDocuments());
                  }
                else{
                  seeSnackBar(context);
                }
              },
              child: Icon(
                  Icons.add,
                  color: Colors.white,
              ),
              backgroundColor: Colors.deepOrangeAccent,
            ),
          ]
      ),
      body:_sublingList(),
    );
  }
  Widget _sublingList(){

    if(subling!=null){
      return ListView.separated(
        itemCount: subling.documents.length,
        padding: EdgeInsets.all(5.0),
        itemBuilder: (context, i){
          return ListTile(
            leading: Icon(Icons.account_circle,
            size: 60.0,),
            title: Text(subling.documents[i].data['nomComplet'],
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontFamily: 'OpenSans'
            ),),
            subtitle: Text(subling.documents[i].data['ldNais'] +'\n'+subling.documents[i].data['adresse']),
            onTap: (){
              updateDialog(context, subling.documents[i].documentID);
              PaiementStripe().getMembers().then((result){
                setState(() {
                  subling = result;
                });
              });
            },
            onLongPress: (){
              showSnackBar(context,subling.documents[i].documentID);
            },
          );
        },
        separatorBuilder: (context, i){
          return Divider();
        },
      );
    }
    else{
      return Center(
        child: CircularProgressIndicator(),
      );
    }
  }
}

当我按下fab按钮时,我收到此消息:

Instance of Future'dynamic'
5 //which is the number of documents

这就是为什么不可能比较它

flutter google-cloud-firestore
2个回答
0
投票

你需要等待Future功能完成

onPressed: () async {
 //the test comparison
     int count = await countDocuments();
     if (count < 5){
        addDialog(context);
        print(countDocuments());
     }
     else{
        seeSnackBar(context);
     }
},

0
投票

你可以做到这一点

void getCount(){   
   countDocuments().then((count ) {
           // print(result);
           if (count < 5){
             addDialog(context);
             print(countDocuments());
           }
           else{
             seeSnackBar(context);
           }
      });
}
© www.soinside.com 2019 - 2024. All rights reserved.