Home > Enterprise >  The property 'color' can't be unconditionally accessed because the receiver can be &#
The property 'color' can't be unconditionally accessed because the receiver can be &#

Time:03-24

How to fix this error. Message error: The property 'color' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!'). enter image description here

My code

@override
  void didChangeDependencies() {
    super.didChangeDependencies();

    // defaults for styles
    // ignore: deprecated_member_use
    selectedDateStyleColor = Theme.of(context).accentTextTheme.bodyText1.color!; //ERROR
    selectedSingleDateDecorationColor = Theme.of(context).colorScheme.seconday;

CodePudding user response:

Replace

selectedDateStyleColor = Theme.of(context).accentTextTheme.bodyText1.color!;

with

selectedDateStyleColor = Theme.of(context).accentTextTheme.bodyText1!.color;

or

selectedDateStyleColor = Theme.of(context).accentTextTheme.bodyText1?.color ?? Colors.black;

It's the bodyText1 that can be null. In the latter case, you'll have to provide a default value as well for when that happens (like I did with Colors.black).

EDIT: when using the bang operator, the code will crash when the bodyText1 is null. Not that I've seen that happen with Theme-related variables until now, but I prefer using ? over ! whenever I haven't checked explicitly that the variable isn't null.

Here's a good read on that matter.

CodePudding user response:

You can use

  if(Theme.of(context).accentTextTheme.bodyText1 != null){
  if(Theme.of(context).accentTextTheme.bodyText1!.color != null){
    Theme.of(context).accentTextTheme.bodyText1!.color!;
  }
}

but also:

Theme.of(context).accentTextTheme.bodyText1?.color?;

REMEMBER : Sound null safety makes types in code non-nullable by default and enables special static checks and compiler optimizations to guarantee that null-dereference errors won’t appear at runtime because they will be spotted at compile-time and fixed. Soundness means that you can trust the type system when it determines that something isn’t null because it can never make a mistake. You can achieve soundness only if all libraries you use in the project have null-safe code.

  • Related