Meggy
Meggy

Reputation: 1691

Flutter/Dart - Null Check Error with data provided by PageViewBuilder

I'm getting the following nullcheck errors on data provided by a PageViewBuilder;

The following _CastError was thrown building:
Null check operator used on a null value

When the exception was thrown, this was the stack: 
#0      _StageBuilderState.createViewItem (package:speakoholic/screens/mainStage.dart:488:161)
#1      _StageBuilderState.build.<anonymous closure> (package:speakoholic/screens/mainStage.dart:138:18)

Line 488 is speakcraft.tagname! when calling this function;

child: editIcon(
       context: context, 
       userid:speakcraft.userid!, 
       audioid:speakcraft.audioid!, 
       title: speakcraft.title!, 
       tagname:speakcraft.tagname!),

And line 138 is the createViewItem

   PageView.builder(
    itemCount: widget.speakcrafts.length,        
    itemBuilder: (context, int currentIndex) {
      return createViewItem(widget.speakcrafts[currentIndex], context, currentIndex, widget.speakcrafts.length );
    },       
  ); 

Heres' the function;

Widget editIcon({
  required BuildContext? context, 
  required int? userid, 
  required int? audioid, 
  required String? title, 
  required String? tagname}) {
  return
    FutureBuilder<int?>(                       
        ///some stuff
    );
}

How do I resolve these nullcheck errors?

Upvotes: 0

Views: 156

Answers (1)

zpouip
zpouip

Reputation: 787

The problem is that you are trying to use a non-nullable value with using a Bang ! operator (also known as null-assertion operator) to cast away nullability: tagname:speakcraft.tagname!.

On the other hand, your property is nullable as String? tagname means that tagname can be null.

So, in order to avoid this you can change your editIcon method:

editIcon(
   ...
   tagname:speakcraft?.tagname ?? 'some default value'),

Upvotes: 1

Related Questions