Method 'replaceFirst' cannot be called on 'String?' - flutter

Error: Method 'replaceFirst' cannot be called on 'String?' because it is potentially null.
Try calling using ?. instead.)
.replaceFirst(r'$selectedRowCount', formatDecimal(selectedRowCount));

As Saffron-codes says, you cant do a replaceFirst on a 'String?' variable since it can be null, and dart is null safe.
There's two options for you to do. You can either make the variable a 'String' instead, if you do this you'll have to give it a value when initiating it:
String variableName = ''
Instead of:
String? variableName
You could also do a null-check (adding a questionmark before .replaceFirst) when calling replaceFirst, this is what it suggests doing in the error message 'Try calling using ?. instead.':
variableName?.replaceFirst(r'$selectedRowCount', formatDecimal(selectedRowCount));

Add the ! operator before . to make it non-nullable
!.replaceFirst(r'$selectedRowCount', formatDecimal(selectedRowCount));

Related

Why/how does type casting solve the null safety error in some cases?

After upgrading to Flutter 3, I am going through my code and correcting null safety errors. Occasionally, I get an error that is fixed by type casting, but I don't understand why. Can anyone help me understand this or point me to a good explanation?
Here's an example:
The code below throws the error: The property 'latitude' 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 ('!').
CameraPosition( target: LatLng( _initLoc.latitude, _initLoc.longitude), zoom: 18)
When I use _initLoc? it throws this error: The argument type 'double?' can't be assigned to the parameter type 'double'.
I can fix it by changing the ? to !, but prefer not to use ! if possible. I discovered that I can keep the ? as long as I cast the latitude and longitude as doubles like below:
CameraPosition(target: LatLng( _initLoc?.latitude as double, _initLoc?.longitude as double),zoom: 18 )
Any explanation for why this works would be appreciated. Thanks.
It is very simple. Just read any variable declared with ? at the end of datatype as 'type' or 'null'. For example if you declared a variable as 'double?', you should read this as 'double' or 'null'. Means the value you are assigning to the variable could be 'double' or 'null'.
The '_initLoc' variable is a nullable type. So it either can be 'type' or 'null'. If it is 'null', you cannot access 'latitude' param inside '_initLoc' object. The '_initLoc?.location' says the compiler only access 'location' param only if '_initLoc' param is not null.
The code '_initLoc?.latitude as double' works as long as '_initLoc' is not null. If it results in null, you again get an error says 'null is not a subtype of double'.
The proper solution would be go to the declaration of '_initLoc' and make it non nullable(without ? at the end of datatype) or if it could be null, pass default value if '_initLoc' is 'null', like CameraPosition(target: LatLng( _initLoc?.latitude ?? 0.0, _initLoc?.longitude ?? 0.0),zoom: 18 )
The '_initLoc?.latitude ?? 0.0' line says, if '_initLoc' is not null access '_initLoc.latitude' param. It '_initLoc' is null, pass '0.0'.
Read the null-safety documentation for deep understanding.
Hope it helps! Happy coding :)

What does the '!' at the end of my code do?

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!
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}");
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
It means it is a nullable type, which means it can be initialized without any value.

Dart null safety !. vs ?-

what is the difference exactly between
String id = folderInfo!.first.id; //this works
and
String id = folderInfo?.first.id; //this is an error
I know ?. returns null when the value object is null but what does the !. return?
?. is known as Conditional member access
the leftmost operand can be null; example: foo?.bar selects property bar from expression foo unless foo is null (in which case the value of foo?.bar is null)
In your case, String id means id can not have null value. But using ?. can return null that's why it is showing errors.
!. is use If you know that an expression never evaluates to null.
For example, a variable of type int? Might be an integer, or it might be null. If you know that an expression never evaluates to null but Dart disagrees, you can add ! to assert that it isn’t null (and to throw an exception if it is).
More and ref:
important-concepts of null-safety and operators.
The Assertion Operator (!)
Use the null assertion operator ( ! ) to make Dart treat a nullable expression as non-nullable if you’re certain it isn’t null.
In other words !. will throw an error if the value is null and will break your function and as you know ?. will return null with no interruption.
The ! throws an error if the variable is null. You should try to avoid this if possible.
If you’re sure that an expression with a nullable type isn’t null, you can use a null assertion operator (!) to make Dart treat it as non-nullable. By adding ! just after the expression, you tell Dart that the value won’t be null, and that it’s safe to assign it to a non-nullable variable.
In your first case, you define id not nullable but when you set nullable value then throw error.
String id = folderInfo?.first.id;
In 2nd case, when you use assertion operator (!), it actually tell compiler that it must be non nullable.

variable changing property is not working in dart programming

void main() {
var a,b;
print("Enter the value of a & b : ");
a=int.parse(stdin.readLineSync());
b=int.parse(stdin.readLineSync());`enter code here`
print("Addition: ${a+b}");
print("Subtraction: ${a-b}");
print("Multiplication: ${a*b}");
print("Division: ${a/b}");
print("Mod: ${a%b}");
}
above code I have using for dart. my problem is whenever I pretend to change the variable to a integer or double value not allowing to run:
Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't b=int. parse(stdin. read Line Sync());
above kind of error throwing. please can anyone help me to understand. because maybe I have made a wrong input or missed something. thank you in advance.
It's a error related to the new Null Safety in Flutter, your variable is nullable because it has the "?" after "String". You just have to add a "!" after the variable that's throwing the error.

The argument type 'String?' can't be assigned to the parameter type 'String'

when I upgrade my flutter to 2.0.1, shows this error:
The argument type 'String?' can't be assigned to the parameter type 'String'.
this is my code:
enum SubStatus {
SUB,
UNSUB,
}
extension ResponseStatusExtension on SubStatus{
static const statusCodes = {
SubStatus.SUB: "sub",
SubStatus.UNSUB: "unsub",
};
String? get statusCode => statusCodes[this];
}
This is how to use it:
String url = "/post/sub/source/" + subStatus.statusCode + "/" + channelId;
this is the error UI:
what should I do to fix it? I tried to return String but in the enum code tell me should return String?:
what should I do?
Change the return type of statusCode to String and provide a default value.
String get statusCode => statusCodes[this] ?? '';
When accessing a map, there is a chance that you will get a null return value if the key does not exist in the map. Simply providing a default value will allow this code to compile. That default value should never be used unless you add something to the enum without adding a value to the map as well.
Edit:
After the comment from #Christopher Moore, I realized my mistake. So, I am going to directly use his solution over here as it is the correct one.
This is because of the new null-safety feature of Dart.
You will need to make the following change in the code and it will work:
String get statusCode => statusCodes[this] ?? '';
With new null-safety rules, the following data-type? x, the data type is followed by a question mark, means that the value x can be null. However, without the '?', it means that data-type x, it cannot be null.
So, basically String and String? are two different data types. That is why you get the error.
You can learn more here.
restart analysis server
add !
like this
subStatus.statusCode!