Home > OS >  The property can't be unconditonally accsessed because the receiver can be null, flutter locali
The property can't be unconditonally accsessed because the receiver can be null, flutter locali

Time:09-01

What's up some guys... I am in the process of making my app available in different countries and I am doing that with flutter_localizations and intl. Everything went smooth up until the very end where I actually use the text from the different language files. Basically I'm trying to add the localization text instead of my hardcoded text, see below.

var text = AppLocalizations.of(context);
Text(text.appTitle),

In my Text widget I get the following error: "The property 'appTitle' can't be unconditionally accessed because the receiver can be 'null'". Is there a good workaround for this? Appreciate any help!

CodePudding user response:

For Text you can do, because the text can be null while reading AppLocalizations.of(context).

Text("${text?.appTitle}"),

This will show null, if it doesn't find the value.

Or checking

if(text!=null) Text("${text!.appTitle}"),

Use ! when you are certain it won't be null.

CodePudding user response:

Since the value could be null at some point it's best to have a default value to display something in case there's no text to show. You can use the null check operator ?? in order to display a placeholder in case the value is null.

Your code will look something like this:

var text = AppLocalizations.of(context);
Text(text?.appTitle ?? 'this text is shown if app title is null')

  • Related