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

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!

Related

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

Unable to put function in validator in flutter

class StudentValidationMixin{
String validateFirstName(String value){
if(value.length<2){
return "Name must be at least two characters";
}
}
}
I am trying to use the feature of the container function and when I come to the validator part, I cannot run the code I mentioned above. I'm facing a problem as I wrote below
The body might complete normally, causing 'null' to be returned, but
the return type, 'String', is a potentially non-nullable type.
body: Container(
margin: EdgeInsets.all(20.0),
child: Form(
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText:"Öğrenci Adı",hintText: "Engin"),
validator: validateFirstName,
onSaved: (String value){
student.firstName=value;
},
naturally I get an error in this (validator: validateFirstName) part as well and this is the error I get
The argument type 'String Function(String)' can't be assigned to the
parameter type 'String? Function(String?)?'.
I couldn't find this answer anywhere but I know the answer is hidden somewhere, I finally gave up and wanted to ask here. How do I fix this error? The trainer I learned Flutter can run this function without having these problems.
As you rightly said the answer is hidden somewhere, indeed it is.
Problem:
The body might complete normally, causing 'null' to be returned, but the return
type, 'String', is a potentially non-nullable type.
The argument type 'String Function(String)' can't be assigned to the parameter type
'String? Function(String?)?'.
Reason:
I don't know about "Jack of all Trade" VSC, but, in Android studio, when you hover the cursor over any paramter, a pop-up tells you what type of input it takes.
So, for the paramter validator in TextFormField, the type acceptable in new Flutter versions which support Null Safety is String? Function(String?)? as you can see in the below image:
But, it worked in the (old) video you watched because in versions lower than Flutter 2.0 (Null Safety), the type was String Function(String) as you can see in the image below:
Now, you can figure out the error you're getting is indeed related to versions. Because, you're trying to use the old type in the new version as with this function:
class StudentValidationMixin{
String validateFirstName(String value){
if(value.length<2){
return "Name must be at least two characters";
}
}
}
Solution:
Change your validator() type as below:
class StudentValidationMixin{
String? validateFirstName(String? value) {
if(value.length<2){
return "Name must be at least two characters";
} else {
return null;
}
}
}
See, what we did there? We changed the return type to nullable, which means the value can be null and it should be in case when the validator validates the string correctly. As what it returns is the error in validation, and when there's no error, null should be returned.
Adding the ? mark means telling the compiler that the particular variable's value can be null and of type given. For example The value of int? count can be either integer or null, whereas the value of int count can only be an integer and will produce NullPointerException if it isn't an integer.
Also, comes with NullSafety is the exclaimation mark ! which tells the compiler that even when the variable was declared nullable, at this point, the value is not null. For ex. variable declared as int? count, value entered into it and when you use it. use it as count! to tell the compiler, at this point, there's a value in it.

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

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

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.

Flutter class error , Try adding an initializer expression, or add a field initializer in this constructor, or mark it [duplicate]

This question already has an answer here:
How do I initialize non-nullable members in a constructor body?
(1 answer)
Closed 1 year ago.
Hi I'm trying to create generic API response class in flutter application and I'm getting this error
class ApiResponse<T> {
Status status;
T data;
String message;
ApiResponse.loading(this.message) : status = Status.LOADING;
ApiResponse.completed(this.data) : status = Status.COMPLETED;
ApiResponse.error(this.message) : status = Status.ERROR;
#override
String toString() {
return "Status : $status \n Message : $message \n Data : $data";
}
}
enum Status { LOADING, COMPLETED, ERROR }
IDE complains about below error
Non-nullable instance field 'data' must be initialized.
Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'
Could anyone tell me what is wrong wiht my code?
It is because like the error says, data field has a non-nullable type T. If you want to allow null for the field data, you will need to make its type nullable by putting a ? like so.
T? data;
Similarly, you will also need to make message field nullable.
String? message;
To see other ways you can go about this and to understand null-safety better, I'd suggest reading this.