Flutter - NoSuchMethodError: The getter 'length' was called on null

Flutter - NoSuchMethodError: The getter 'length' was called on null

我正在尝试从 Flutter 中的 JSON rest API 获取平均评分列表。当所有产品都有评级值时,列表视图显示正常,但当任何产品的评级为空时,列表视图 returns 出现错误“NoSuchMethodError:getter 'length' 被调用为空。接收器: null。尝试调用:length。以下是我的代码;

                             ListView.separated(
                                  separatorBuilder: (context, index) =>
                                      Divider(
                                        color: Colors.grey,
                                      ),
                                  padding: const EdgeInsets.all(5.0),
                                  itemCount: content.length,
                                  itemBuilder: (context, position) {
                                 final current = content[position];
                                    double myrate = double.parse(content[position].ratings);
                                    return Container(

                                           child: SmoothStarRating(
                                                    allowHalfRating: true,
                                                    onRatingChanged: (v) {
                                                    setState(() {});
                                                     },
                                                    starCount: 5,
                                                    rating: myrate,
                                                    halfFilledIconData: Icons.star_half,
                                                    size: 20.0,
                                                    filledIconData: Icons.star,
                                                    color: Colors.orange,
                                                    borderColor: Colors.orange,
                                                    spacing: 0.0)

                                                     )

                                            })

您应该在代码中考虑所有情况。例如,当列表为空或为空时,您应该向用户显示其他内容。您应该将代码更改为如下内容:

Container(
   child: content.length > 0 
   ? ListView.separated()
   : Text('there is no rate for this ...'),
)

如果您的数据可为空,请将您的条件更改为:

    Container(
       child: (content?.length ?? 0) > 0 
       ? ListView.separated()
       : Text('there is no rate for this ...'),
    )

所以我能够通过简单地添加当我的评分为空时返回“0”和当它不为空时的实际值来解决这个错误。使用这行代码:

double myrate = double.parse( content[position].ratings==null ? "0" : content[position].ratings);