【问题标题】:type 'Future<dynamic>' is not a subtype of type 'double''Future<dynamic>' 类型不是 'double' 类型的子类型
【发布时间】:2020-01-04 15:51:21
【问题描述】:

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

类型'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,
  ),
),

【问题讨论】:

  • 一旦将 calculateEvaluations 定义为异步函数,它就会变成 Future,而不是 double。你应该 await 使用它作为一个 double,换句话说,你应该等待未来解决

标签: flutter dart


【解决方案1】:

这是我所做的:

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

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,
  ),
)

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

希望这会有所帮助。我没试过。如果出现问题,请告诉我。

【讨论】:

  • 很高兴听到这个消息。
猜你喜欢
  • 2020-09-24
  • 2020-09-11
  • 2020-10-13
  • 2021-02-10
  • 1970-01-01
  • 2020-01-14
  • 2021-08-29
  • 2023-03-27
  • 1970-01-01
相关资源
最近更新 更多