A nullable expression can't be used as a condition. Try checking that the value isn't 'null' before using it as a condition

Issue

hello everyone I had this code where I want to make a condition if there is data a specific icon will appears if there is no data another specific icon will appear but this error has been appearing to me ‘shown in the title of the question ‘ and I had no idea how I can solve it

this is the code and the error is in line four

                        IconButton(
                          // ignore: unnecessary_new
                          icon: new Icon(
                              snapshotflag.data
                                  ? Icons.flag_circle_outlined
                                  : Icons.flag_circle,
                              color: Colors.red,
                              size: 30.0),
                          onPressed: () {
                            _postService.flagPost(
                                Post, snapshotflag.data);
                          },
                        ),

the definition of snapshot flag and it is type

StreamBuilder(
                  stream: _postService.getcurrentUserFlag(Post!),
                  builder: (BuildContext context,
                      AsyncSnapshot<bool> snapshotflag)

Solution

You cannot use nullable value as a condition.
Try adding the ?? operator that returns if the expression is a null like below.

IconButton(
  // ignore: unnecessary_new
  icon: new Icon(
      snapshotflag.data ?? false  // <-- Here
          ? Icons.flag_circle_outlined
          : Icons.flag_circle,
      color: Colors.red,
      size: 30.0),
  onPressed: () {
    _postService.flagPost(
        Post, snapshotflag.data);
  },
)

Answered By – MaNDOOoo

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.