returnMap[date]++; error : The method '+' can't be unconditionally invoked because the receiver can be 'null' - flutter

Hello I try to make null safety migration, but I have an error with ++ from returnMap[date]++; . I don't know how to write correctly in null stafety. Thank you
Here is my code
thank you
for (var i = x; i < list_conso.length; i++) {
DateTime parsedDate = DateTime.parse(list_conso[i]);
String date = "${parsedDate.year}-${parsedDate.month}-${parsedDate.day}";
date = DateFormat('yyyy-MM-dd').format(parsedDate);
if (returnMap.containsKey(date)) {
returnMap[date]++; //The method '+' can't be unconditionally invoked because the receiver can be 'null'
} else {
returnMap[date] = 1;
}
}

Since you have checked that returnMap contains date, you can use:
returnMap[date]!++;
The exclamation mark tells the compiler you are sure that returnMap[date] exists and is not null.

Related

dart null safty issue when try to add value to map element

I am using Dart but i am facing null safty issue with following code
RxMap<Product,int>cartItems=Map<Product,int>().obs;
void updateCart(Product product,String type){
if(type=="plus") {
cartItems.value[product]++;
}
else {
cartItems.value[product]--;
}
}
i got the following error message
the method '+' can't be unconditionally invoked because the receiver can be 'null'
i tried to add null check to the target as following
cartItems.value![product]++;
You can give a default value if null.
cartItems.value[product]??0 +1
Or force assert to non null value like this.It may throw exception if element not present in HashMap
cartItems.value[product]!+1
In your question you are asserting not null for HashMap not the value of the HashMap.
The problem is that cartItems.value is a Map and it's possible that cartItems.value[product] is null. In this case you can't add or remove 1 to null.
So you should do like the following:
if (type == "plus") {
cartItems.value[product] = (cartItems.value[product] ?? 0) + 1;
} else {
cartItems.value[product] = (cartItems.value[product] ?? 0) - 1;
}
Using (cartItems.value[product] ?? 0) you're saying that if cartItems.value[product] is null 0 is used instead.
Also note that in the else clause, when cartItems.value[product] == null, you're trying to remove 1 to something that doesn't exist, so in that case it may be best to throw an exception:
int? currentValue = cartItems.value[product];
if (currentValue == null) {
throw Exception('Trying to remove on a null object');
}
cartItems.value[product] = currentValue - 1;

Check variable run time Type in flutter with conditions like "123" is present as a String but is a int so how can i check this?

I have to check runtime Type of value for this I am using :-
for Example:-
String a = "abc";
int b = 123;
var c = "123"; //this is int value but because of this double quotes is represent as a String
a.runtimeType == String //true
b.runtimeType == int // true
c.runtimeType == String //true
c.runtimeType == int //false
a = "abc" // okay
b = 123 //okay
c = "123" //is issue
now I have to call a api with only String body in this case :-
this c is called the API because is String but i know this is a int value which is present as a String, so I have to stop this.
How can I check this??
when I am using try catch so my program is stopped because of FormatException error.
Note:- I don't know the real value of C, may be its "123" or "65dev" or "strjf" this value is changed every time.
and if i am parsing this in int to this return an error in many case.
Ok i understood that you want to pass "123" by checking and if it is int you are passing it , My question is what you will do if it is "123fe" you are going to pass as string? or you will pass nothing.
I don't know how you're passing it to API but if you wanna pass integer value from string quoted variable, you can parse/convert to integer like this.
int.parse(c);
either you can pass it directly or you can store in another variable and pass that variable.
Alternatively if you've int value and to have to pass it as a string, simply parse like this
integerValue.toString();
according to your code
b.toString();
Edit
String a = '20';
String b = 'a20';
try{
int check = int.parse(a);
//call your api inside try then inside if
if(check.runtimeType == int){
print('parsed $check');
}
}
catch(e){
print('not parsed ');
//handle your error
throw(e);
}
This will definitely help you!
String name = "5Syed8Ibrahim";
final RegExp nameRegExp = RegExp(r'^[a-zA-Z ][a-zA-Z ]*[a-zA-Z ]$');
print(nameRegExp.hasMatch(name));
//output false
name = "syed ibrahim";
print(nameRegExp.hasMatch(name));
//output true
Just check the output and based on that boolean value invoke api call
I hope it will done the work

Conditional Operators (??) issues in dart

void main() {
print("Conditional Operators:");
// small if else
var a1 = 100;
var b2 = 20;
var istrue = (a1 < b2) ? 'True' : 'False';
print(istrue);
// check if null or print name
var name1;
var check = name1 ?? "This is Null";
print(check);
var name = "Abdulelah";
var checknot = name ?? "This is Null";
print(name);
}
I don't how i fix this problem in line 16
yellow error said:
The left operand can't be null, so the right operand is never executed.
Try removing the operator and the right operand.dartdead_null_aware_expression
The variable "name" won't be NULL because you give to him the value "Abdulelah", so the right part ?? "This is NULL" won't be executed, remove this right part and the warning will disappear.
Using ?? we provide default value in null case.
a = x ?? y
The above example shows that if x return/becomes null, y will be initialized on a. The fact becomes.
if x is not null, then a = x
if x is null, then a = y
Instead of using if, else we use ?? to provide null handler value.
The editor is acting smart here because it knows that name is not null, so the yellow message is saying you don't need to provide default value because left expression will never be null.
To create null variable, you need to use
DataType? variableName;
In this case you are initializing String and you can do
String? name = "Abdulelah";
But this is not needed unless you want to initialize null value on name variable.
You can check
Difference between var and dynamic type in Dart?
and dart.dev for more.

Error: A value of type 'num?' can't be assigned to a variable of type 'num' because 'num?

I found this error while running the dart project
Error: A value of type 'num?' can't be assigned to a variable of type 'num' because 'num?'
import 'dart:io';
void main() {
print("Enter your birth-year");
var n = num.tryParse(stdin.readLineSync() ?? "");
if(n=="") {
print("Bad Year");
}
var age = DateTime.now().year-n;
print(" ==> You are $age year old!");
}
As you can read in the documentation of num.tryParse, the method has an return type of num?. This implies that your variable n is also of the type num? (Nullable num).
So the error points you to the line, where you want to subtract an nullable number from DateTime.now().year, which is not allowed.
You can workaround this limitation by using the ?? (Null coalescing) operator and checking for null and if your n is null subtract 0.
var age = DateTime.now().year - (n ?? 0) ;
Another solution is, just using an if checking for null followed by an else block, like:
if(n == null) {
print("Bad Year");
}
else {
var age = DateTime.now(). year - n ;
print(" ==> You are $age year old!");
}
Taking up your comment:
i added ! after n and works fine... that is the same solution?
Adding the null-assertion operator (!) to the n in DateTime.now().year - n! is not the same solution, but it is a possible solution. And as you already mentioned it compiles and work.
But be careful:
You are telling the compiler that you are sure, that n will never be null.
With your current code you will get an runtime error, when the user enters a letter or nothing. Then the parsing of that string fails and your n is null. And now you want to subtract null from the DateTime.now().year, which is again not allowed.
You can read more about Null-Safety on https://dart.dev/codelabs/null-safety .
Side note:
The following check is not correct:
if(n=="") {
print("Bad Year");
}
If an incorrect number was entered, your n is null and this is not equal to an empty string. To get your if clause work, simply use a null check. I also recommend to add a return after the output, otherwise your person gets quite old.
if(n == null) {
print("Bad Year");
return;
}

Javascript create a function that returns a boolean value based on certain parameters

Thanks for taking the time to look at my problem. What I'm trying to do is create a javascript function that tests whether a sting is a particular length and also whether each element of that string can be found in another string. The function then needs to return a boolean value of either true or false depending on whether the string is valid.
Here's what I have:
N_ALPHA = 6;
N_CHOICES = 4;
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var alphabet = ALPHABET.substring(0, N_ALPHA);
function isValidGuess(inStr)
{ var valid;
var Str = inStr;
for (i=0; i<Str.length; i++)
{ if (Str.charAt(i) === alphabet.charAt(i) && Str.length == N_CHOICES.length)
{ valid = true;
}
else
{ valid = false;
}
}
return valid;
}
This code is not working at all. It only returns false every time. Any help you could provide would be greatly appreciated. Thank you.
N_CHOICES.length return undefined, because variable N_CHOICES is number.
you have to change your condition to
if (Str.charAt(i) === alphabet.charAt(i) && Str.length == N_CHOICES)