The argument type 'String?' can't be assigned to the parameter type 'String' in flutter for shared prefrances - flutter

so I am using shared preferences in a flutter app and I get this error :
The argument type 'String?' can't be assigned to the parameter type 'String'
and here is the code:
if (result != null) {
SharedPreferenceHelper().saveUserEmail(userDetails.email);
}
the error is userDetils.email can someone pls help
A picture of what it shows

Those are two different types. You need to coerce String? to String either by the null coercion operator: userDetails.email! or by giving it a default value if it's null: userDetails.email ?? ''

After looking into the image posted the line 30 declaration states that:
User? userDetails = result.user;// Which potentially means that variable userDetails could be null
Where as the class User details are not shared but peaking into the issue I am pretty sure the class User has a email parameter whose declaration is as includes it's datatype as String? email something like this with prefix of final or late.
In this case what happens is that you have nested level of nullity for accessing email variable out of userDetails object.
Which means:
Case 1=> userDetails is null and email is null.
Case 2=> userDetails is not null and email is null.
Case 3=> userDetails is not null and email is not null.
Meaning both `userDetails` and `email` have a datatype of which defines them to be null at compile time.
Since dart is statically typed language so you need to add in ! after each variable whose datatype is nullable at compile time to allow dart know that the variable has data in it and was assigned a value sometime later in run time.
So to fix this what you need to do is that replace the line below with line 33:
SharedPreferenceHelper().saveUserEmail(userdetails!.email ?? "Some default email");
// if you never want to save null as email pref else use the one below
SharedPreferenceHelper().saveUserEmail(userdetails!.email.toString());

It is sound null safety problem
String? means Whatever variable assigned to Stirng? type it can be null or null value is available
,so make sure to check it null or not by providing userDetils.email?? this means userDetils.email is null or not

Related

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.

Can't assign non-nullable type to a nullable one

error: The argument type 'Future<List<GalleryPictureInfo>>' can't be assigned to the parameter type 'Future<List<GalleryPictureInfo>>?'.
Is this Dart Analysis or me? The project still compiles.
Upd. Added code example
FutureBuilder<List<GalleryPictureInfo>>(
future: derpiService.getListOfImages(),
//other code
);
#override
Future<List<GalleryPictureInfo>> getListOfImages(arguments) async {
List<GalleryPictureInfo> listOfImages = [];
var searchImages = await getSearchImages(tags: tags, page: page);
//adding images to List
return listOfImages;
}
It's something with FutureBuilder actually. I should've mention this.
Upd. "Fixed" with // ignore: argument_type_not_assignable
Looks like a problem with Dart Analysis for now
Upd. Error
It actually is an error which is pretty self explanatory.
The acutal error comes because of null safety in dart.
For ex:
void main(){
var number = getNumber(true);
int parsedNumber = int.parse(number);
print(parsedNumber);
}
String? getNumber(boolean value) {
if (value){
return null;
} else return "1";
}
So here, getNumber function either returns null or "1" depending upon the value of value variable. So, number variable's type is String?.
But the error shall arise in the next line when you try to call int.parse(). int.parse function takes an argument which should be a String but the value passed in the function is of type String?. So if we pass null in int.parse it shall throw an error.
That's why Dart analysis makes it easier to identify such cases by telling us that the value can be null and it might throw.
However the code depends upon your actual code of your project. It says that you are passing Future<List<GalleryPictureInfo>>? which is of nullable type to a function which requires Future<List<GalleryPictureInfo>>. So, before passing the value you might want to check if the value you are passing is not null.
If you are sure that the value can never be null then if for ex: if you are passing a variable called value, you might wanna try someFunctionWhereYouPassValue(value!)
That ! means that you are sure that the value will never be null.
For more details about null safety you can see:
https://dart.dev/null-safety/understanding-null-safety

What does "!" this operator means in dart when it using like below?

final user = FirebaseAuth.instance.currentUser;
print(user);
if (user!.emailVerified) {
print('User is veryfied');
} else {
print('please verify');
}
Without it I get an error that says Property emailVerified cannot be accessed on User? because it is potentially null
but when I add ? this to avoid it
I get this error A value of type 'bool?' can't be assigned to a variable of type bool because 'bool?' is nullable and 'bool' isn't.
When you add a ? it means that it is can have a value or null. But if you add ! it means that the value cannot be null but we are unsure of the value..
Now for example if you are sure that a user is available then you can add
user!.emailVerified;
if for example you are unsure then you can add
user?.emailVerified
Now if user is null in the second case then it cannot be used in a condition because null is not a condition like true or false. So you may have to supply a default too
(user?.emailVerified ?? false)
This means that if the previous value is null then it will use false

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.

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!