Home > Software design >  What does the '!' at the end of my code do?
What does the '!' at the end of my code do?

Time:09-01

Text(locations[index].location!)

without the '!' I get the next error: The argument type 'String?' can't be assigned to the parameter type 'String'

Thanks in advance!

CodePudding user response:

locations[index].location can return null, using ! we are saying, the value of it won't be null. Text widget doesn't accept null value.

It is better to do a null check 1st on nullable data like

if (locations[index].location != null) Text(locations[index].location!)

or you can provide default value

Text(locations[index].location ?? "got null")

You can also do

Text("${locations[index].location}");

CodePudding user response:

The exclamation mark (!) in Dart tells the code that you are sure this variable can never be null. It is an unsafe way of dealing with variables that may be null.

In your case, the type of the variable is String?, which means that it may be null or a String.

To safely unwrap a nullable variable, it is advised to do the following:

if (locations[index].location != null) {
  //Do your logic here
}

Null Safety Documentation

CodePudding user response:

It means it is a nullable type, which means it can be initialized without any value.

  • Related