如何更有效地编写此Flutter代码?

时间:2019-09-17 12:32:10

标签: flutter dart google-cloud-firestore

正如您在第一部分中看到的那样,我正在检查Firestore的文档中是否包含某个值,并返回布尔值。现在,我在构建中调用该函数,并基于该返回值更改芯片颜色(第二部分)。

现在的问题可能是因为我在构建函数中对其进行了调用,因此在该构建中对其进行连续调用,这使我在Firestore中花费了大量的读取费用,或者该函数效率很低。我如何才能更有效地编写此内容?

checkAtt(String name, id , date) async{
   var ref = _db.collection('subjects').document(id).collection('Att').document(date);
   var docref = await ref.get();
      return docref.data.containsKey(name)
        ?true
        :false;
  }

 class PresentChip extends StatefulWidget {
  final candidate;
  PresentChip(
    this.candidate, {
    Key key,
  }) : super(key: key);
  @override
  _PresentChipState createState() => _PresentChipState();
}

class _PresentChipState extends State<PresentChip> {
  var isSelected = false;
  var c = false;
  @override
  Widget build(BuildContext context) {
    final SelectSub selectSub = Provider.of<SelectSub>(context);
    final Date date = Provider.of<Date>(context);

  db.checkAtt(widget.candidate, selectSub.selectsub, date.datenew).then((result){
    print(result);
    setState(() {
     c = result; 
    });
  }); 

       return Container(
      child: ChoiceChip(
        label: Text('Present'),
        selected: isSelected,
        onSelected: (selected) {
          db.gibAtt(
              widget.candidate, selectSub.selectsub, date.datenew.toString());
          setState(() {
            isSelected = selected;
          });
        },
        backgroundColor: !c ?Colors.red :Colors.green ,
        selectedColor: !c ?Colors.red :Colors.green ,
    ));
  }
}

1 个答案:

答案 0 :(得分:0)

假设您只想从Firestore中读取一次,则需要一个FutureBuilder

return Container(
  child: FutureBuilder(
    future: db.checkAtt(widget.candidate, selectSub.selectsub, date.datenew),
    builder: (context, snapshot) {
      if(snapshot.hasData)
      return ChoiceChip(
        ...
        backgroundColor: !snapshot.data ?Colors.red :Colors.green,
        selectedColor: !snapshot.data ?Colors.red :Colors.green,
      );

      //Return another widget if the future has no data
      return Text('Future has no data');
    }
  )
);

如果您需要UI对Firestore中的更改做出反应,请使用StreamBuilder

您可以从构建方法中删除以下块:

db.checkAtt(widget.candidate, selectSub.selectsub, date.datenew).then((result){
  print(result);
  setState(() {
   c = result; 
  });
});