类型'Future <dynamic>'不是类型'double'的子类型

时间:2019-09-01 02:51:27

标签: flutter dart

我的目标是计算该地点的平均值。但是,当我尝试计算时,我收到此错误:

“ Future”类型不是“ double”类型的子类型

期望是一种双精度类型,因为谁会收到这将是RatingBar。

这是功能代码:

calculateEvaluations() async{
    double average = 0;
    var docs = await Firestore.instance.collection(widget.option).document(widget.document.documentID).collection("comments").getDocuments();
    List<DocumentSnapshot> documents = docs.documents;
    for(int i=0; i<documents.length; i++){
      average = average + documents[i]["rating"].toDouble();
    }

    average = average / documents.length;
    return average;

  }

我将此返回值设置为RatingBar。

Container(
  margin: EdgeInsets.only(left: 5.0),
  child: RatingBarIndicator(
  rating: calculateEvaluations(),
  itemPadding: EdgeInsets.symmetric(horizontal: 2.0),
  itemBuilder: (context, index) => Icon(
    Icons.star,
    color: Colors.yellow,
  ),
  itemCount: 5,
  itemSize: 18.0,
    direction: Axis.horizontal,
  ),
),

1 个答案:

答案 0 :(得分:1)

这是我所做的:

在继承_ratingIndicator=0.0的类中创建类型为double的字段StatefulWidget

void calculateEvaluations(){
    double rating=0.0,average = 0.0;
    int i;
    Firestore.instance.collection("y").document("x").collection("comments").getDocuments()
    .then((documents){
        for(i=0; i<documents.length; i++){
            rating = rating + documents[i]["rating"].toDouble();
        }
        average=rating/documents.length;
        setState(() {
         _ratingIndicator=average; 
        });
    });
  }

然后

Container(
  margin: EdgeInsets.only(left: 5.0),
  child: RatingBarIndicator(
  rating: _ratingIndicator,
  itemPadding: EdgeInsets.symmetric(horizontal: 2.0),
  itemBuilder: (context, index) => Icon(
    Icons.star,
    color: Colors.yellow,
  ),
  itemCount: 5,
  itemSize: 18.0,
    direction: Axis.horizontal,
  ),
)

另外,请不要忘记在calculateEvaluations()方法中调用initState

希望这会有所帮助。我还没试过让我知道是否出现问题。