在 Futerbuilder 中对空值使用的空检查运算符

时间:2021-05-19 04:42:38

标签: flutter

当我运行应用程序时。 我收到一条消息 “用于空值的空检查运算符”。

这是我收到的错误信息。

======== Exception caught by widgets library =======================================================
The following _CastError was thrown building FutureBuilder<List<SocialCommentModel>>(dirty, state: _FutureBuilderState<List<SocialCommentModel>>#d495e):
Null check operator used on a null value

The relevant error-causing widget was: 
  FutureBuilder<List<SocialCommentModel>> file:///C:/Users/user/AndroidStudioProjects/Unikaive/lib/ui/detailedPost/DetailedPostScreen.dart:367:15
When the exception was thrown, this was the stack: 
#0      _DetailedPostScreenState._buildPostWidget.<anonymous closure> (package:unikaive/ui/detailedPost/DetailedPostScreen.dart:381:49)
#1      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:775:55)
#2      StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
#4      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4746:11)
...
====================================================================================================

这是有问题的 FuterBuilder。

FutureBuilder<List<SocialCommentModel>>(
                  future: _commentsFuture,
                  initialData: [],
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return Container(
                        child: Center(
                          child: CircularProgressIndicator(),
                        ),
                      );
                    } else {
                      return ListView.builder(
                        padding: EdgeInsets.only(top: 8, bottom: 60),
                        physics: NeverScrollableScrollPhysics(),
                        itemCount: snapshot.data!.length,
                        itemBuilder: (context, index) {
                          SocialCommentModel comment = snapshot.data![index];
                          return _commentWidget(comment);
                        },
                        shrinkWrap: true,
                      );
                    }
                  }),

我做 flutter doctor 的时候没问题。

请帮忙。

1 个答案:

答案 0 :(得分:0)

将此添加到您的代码中:

if (!snapshot.hadData) {
                      return Container(
                        child: Center(
                          child: CircularProgressIndicator(),
                        ),
                      );
                    }