How to check a string null in Dart? - flutter

How do you check a string for "null" in Dart? (not a null object)
is there some Dart SDK API like Java's equals?

I believe isEmpty property will return false since if your string is null, it still holds an object and won't be empty. So depending on what you mean in your post.
If you want to check for the string 'null', just do
if (stringVar == 'null')
or if you want to check if your string is null, then
if (stringVar == null)

Checking if the string is null:
if (s == null) {
…
}
Checking if the string is not null:
if (s != null) {
…
}
Returning the string if not null, 'other value' otherwise:
return s ?? 'other value'
Assigning a value to the string only if that string is null:
s ??= 'value'
Calling a method (property) on the string if it's not null
s?.length

You can use the isEmpty property.
bool [string name] isEmpty;
Alternatively, you can do this:
String text = "text";
print(text.isEmpty);
Output: false
Edit: I believe that Mohammad Assad Arshad's answer is more accurate. Sorry about that.

In addition to
myString == 'null'
or
myString == null
There is another meaning that "null" could take: the null character. In ASCII or Unicode this has the code value of 0. So you could check for this value like so:
myString == '\u0000'
or
myString.codeUnits.first == 0

Related

firebase security rules: optional field that could be a null or a string?

How to make firebase accept a key that could be a null or a string ? and yet the field is optional, since in security rules you canot ceck if (is) is null ?
function dataCheckCreate(requestData) {
return (
// requestData.count required
requestData.count is number &&
// requestData.src required
requestData.src is string &&
// requestData.date optional !!
// if available it could be a null or a string
(requestData.date == null || requestData.date is string)
);
}
The last rule will be true when date is either equal to null or is a string. If you want that field to be optional then try:
function dataCheckCreate(requestData) {
return (
requestData.count is number &&
requestData.src is string &&
// [date not present in data keys] [date is string]
(!('date' in requestData.keys()) || requestData.date is string)
);
}
You cant store null in a string field on firebase. The equivalent is to not store it at all.
Javascript will set the key date to undefined/null if it doesn't exist.
Since it's either null or string and optional, do you really need to check it? This would be a suitable check:
function dataCheckCreate(requestData) {
return requestData.count && requestData.src
}

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

How to use ternary operator to check if a String is empty in a simple way

I will show in 10 Text widgets, some variables. This variables can are Strings and can be empty ''
There is a simpler way to do this verification than this, one by one: ?
object.name.isNotEmpty ? object.name : "not typed"
try this
check if it is null string
object.name ?? 'default value'
check if its a null or empty string
object.name?.isEmpty ?? 'default value'
The ?? double question mark operator means "if null". Take the following expression, for example. String a = b ?? 'hello'; This means a equals b, but if b is null then a equals 'hello'.
object.name ??= "not typed";
It assigns "not typed" if object.name is empty.
You can also use double question mark to check if something else is null and if it is assign the other value:
object.name = null ?? "not typed"; // result: object.name = "not typed";
object.name = "typed" ?? "not typed"; // result: object.name = "typed";
EDIT:
If you need to check if something is an empty string, you can use tenary expression, but there is no more operators or string methods:
object.name = object.name != null && object.name.isNotEmpty ? object.name : "not typed";
If I understand your question correctly you want to simply check if something is null and assign to a variable accordingly. To do this you can use the OR operator like this:
var x = object.name || "not typed"
if object.name is truthy (as in not an empty string "") then that will be assigned to your variable (in this case x). If object.name is an empty string/falsey then "not-typed" will be assigned to x.
I think that the most convenient way to provide a default value is to extend the String class.
So, create a class StringExtension with a method like this:
extension StringExtension on String {
String def(String defaultValue) {
return isNotEmpty ? this : defaultValue;
}
}
In your view, you can now simply do:
import 'package:code/helpers/string_extension.dart';
String value;
#override
Widget build(BuildContext context) {
return Text(value.def("Unknown"))
}
To check if a string is null or not by using ternary operator in JS you can use:
let n = ""
console.log(n.length > 0 ? "The string is not empty" : "The string is empty");

How to use ternary operator(?:) or Null Coalescing operator(??) to write if-else condition?

if(country1 != null)
{
country1 = "Turkey";
}
else
{
country1 = "ABD";
}
Ternary operators use three operands:
A condition followed by a ?,
followed by an expression to evaluate if the condition is 'truthy', followed by a :,
followed by an expression to evaluate if the condition is falsey.
So in your case, what you'd want to do is this:
country1 = country1 != null ? 'Turkey' : 'ABD';
EDIT:
You seem a little confused about ?? operator. ?? is called Null Coalescing operator
x = x ?? 'foo';
is equivalent to
if( x == null )
x = 'foo';
else
x = *whatever the value previously was*;
so if we have x set to bar before the check, it won't change to foo because bar is not equal to null. Also, note that the else statement here is redundant.
so ?? will set the variable to some value only if it was previously null.
In your code, you are trying to assign one of the two values Turkey or ABD, and not a single value if the previous value was null. So you get a syntax error.
So, to summarize.
if() {}
else {}
can be shortened using the ternary operator ? :.
and
if(){}
can be shortened using the ?? operator, because the else statement here will simply be redundant.
Thus, the equivalent of your code won't use ?? operator.
var s = country1 != null ? "Turkey" : "ABD";
final result = country1 != null ? 'Turkey' : 'ABD';
Syntax:
var result = a != null ? condition is true then further code : condition is false then further code;
in your case :
var result = country1 != null ? "Turkey" : "ABD";
you can do it this way too:
final result = "${country1 != null ? 'Turkey' : 'ABD'}";