Is there a working way to check if a double variable is NaN?
I tried:
variable.isNaN
variable == double.nan
Here the complete code:
bool isValidQuantity(String s) {
double converted = toDouble(s);
if (converted == double.nan || converted < 0) {
return false;
}
return true;
}
toDouble() is a function of the library validators version 2.0.0+1
It just returns double.nan in this case so I don't get why false isn't returned by the isValidQuantity() function
It is working fine. However, you might want to initialize your variable because in dart everything is Object(any int, float, bool etc) and default values of the object are Null.
var myVar = 0.0;
if (myVar.isNaN)
print('Not a number');
else
print('${myVar} is a number');
Related
My current goal is to remove this code duplication:
final int? myNullableInt = 10;
/// Everywhere I need to do this null verification:
if (myNullableInt == null) return null;
return someOtherMethodThatReceivesANonNullableInt(myNullableInt);
I want to convert to something like we have in Kotlin:
final int? myNullableInt = 10;
return myNullableInt?.apply((myInt) => someOtherMethodThatReceivesANonNullableInt(myInt));
I did it:
extension ApplyIfNotNull on Object? {
T? apply<T extends Object?>(Object? obj, T? Function(Object) fn) {
if (obj == null) return null;
return fn(obj);
}
}
But this gives me a static error:
The argument type 'Object' can't be assigned to the parameter type 'int'.
Note: this should work with all types, e.g ints, Strings, double and MyOwnClassTypes.
Is there something I can do? or am I missing something?
extension ApplyIfNotNull on Object? {
T? apply<T extends Object?>(Object? obj, T? Function(Object) fn) {
if (obj == null) return null;
return fn(obj);
}
}
That doesn't work because it declares that the callback be capable of accepting any Object argument, but you're presumably trying to use it with a function that accepts only an int argument. It's also unclear why you've made an extension method since it doesn't involve the receiver (this) at all.
You need to make your function generic on the callback's argument type as well:
R? applyIfNotNull<R, T>(T? obj, R Function(T) f) =>
(obj == null) ? null : f(obj);
(That's the same as what I suggested in https://github.com/dart-lang/language/issues/360#issuecomment-502423488 but with the arguments reversed.)
Or, as an extension method, so that it can work on this instead of having the extra obj argument:
extension ApplyIfNotNull<T> on T? {
R? apply<R>(R Function(T) f) {
// Local variable to allow automatic type promotion. Also see:
// <https://github.com/dart-lang/language/issues/1397>
var self = this;
return (self == null) ? null : f(self);
}
}
Also see https://github.com/dart-lang/language/issues/360 for the existing language feature request and for some other suggested workarounds in the meantime.
Let's say I have:
class Test<T> {
void method() {
if (T is int) {
// T is int
}
if (T == int) {
// T is int
}
}
}
I know I can override == operator but what's the main difference between == and is in Dart if I don't override any operator.
Edit:
Say I have
extension MyIterable<T extends num> on Iterable<T> {
T sum() {
T total = T is int ? 0 : 0.0; // setting `T == int` works
for (T item in this) {
total += item;
}
return total;
}
}
And when I use my extension method with something like:
var addition = MyIterable([1, 2, 3]).sum();
I get this error:
type 'double' is not a subtype of type 'int'
identical(x, y) checks if x is the same object as y.
x == y checks whether x should be considered equal to y. The default implementation for operator == is the same as identical(), but operator == can be overridden to do deep equality checks (or in theory could be pathological and be implemented to do anything).
x is T checks whether x has type T. x is an object instance.
class MyClass {
MyClass(this.x);
int x;
#override
bool operator==(dynamic other) {
return runtimeType == other.runtimeType && x == other.x;
}
#override
int get hashCode => x.hashCode;
}
void main() {
var c1 = MyClass(42);
var c2 = MyClass(42);
var sameC = c1;
print(identical(c1, c2)); // Prints: false
print(identical(c1, sameC)); // Prints: true
print(c1 == c2); // Prints: true
print(c1 == sameC); // Prints: true
print(c1 is MyClass); // Prints: true
print(c1 is c1); // Illegal. The right-hand-side must be a type.
print(MyClass is MyClass); // Prints: false
}
Note the last case: MyClass is MyClass is false because the left-hand-side is a type, not an instance of MyClass. (MyClass is Type would be true, however.)
In your code, T is int is incorrect because both sides are types. You do want T == int in that case. Note that T == int would check for an exact type and would not be true if one is a derived type of the other (e.g. int == num would be false).
Basically, == is equality operator and "is" is the instanceof operator of Dart (If you come from Java background, if not, it basically tells you if something is of type something).
Use == for equality, when you want to check if two objects are equal. You can implement the == operator (method) in your class to define on what basis do you want to judge if two objects are equal.
Take this example:
class Car {
String model;
String brand;
Car(this.model, this.brand);
bool operator == (otherObj) {
return (otherObj is Car && other.brand == brand); //or however you want to check
//On the above line, we use "is" to check if otherObj is of type Car
}
}
Now you can check if two cars are "equal" based on the condition that you have defined.
void main() {
final Car micra = Car("Micra", "Nissan");
print(micra == Car("Micra", "Nissan")); // true
print(micra is Car("Micra", "Nissan")); // true
}
Hence, == is something you use to decide if two objects are equal, you can override and set it as per your expectations on how two objects should be considered equal.
On the other hand, "is" basically tells you if an instance is of type object (micra is of type Car here).
How do I check if a value is a number (even or odd) with type double in Dart?
double value = 2.5;
print(value.floor().isEven ? "It's even" : "It's odd");
You can go traditional with String evenOrOdd = number %2 == 0?'even':'odd'
There are native methods for int to achieve that purposes. You can convert the number to an int and call number.isOdd, number.isEven...
Documentation:
abstract class int extends num {
/// Returns true if and only if this integer is odd.
bool get isOdd;
// Returns true if and only if this integer is even.
bool get isEven;
}
Here is the code to detect from String.
bool isDouble(String? s) {
if (s == null) {
return false;
}
if(int.tryParse(s)!=null){
return false;
}
return double.tryParse(s)!= null;
}
I'm having a list of different types of values exported from JSON.
class StudentDetailsToMarkAttendance {
int att_on_off_status;
String name;
String reg_number;
int status;
StudentDetailsToMarkAttendance(
{this.att_on_off_status, this.name, this.reg_number, this.status});
factory StudentDetailsToMarkAttendance.fromJson(Map<String, dynamic> json) {
return StudentDetailsToMarkAttendance(
att_on_off_status: json['att_on_off_status'],
name: json['name'],
reg_number: json['reg_number'],
status: json['status'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['att_on_off_status'] = this.att_on_off_status;
data['name'] = this.name;
data['reg_number'] = this.reg_number;
data['status'] = this.status;
return data;
}
}
I am trying to use the value of status as the value parameter of Checkbox. I am trying to parse int to String like this.
value:((widget.studentDetailsList[index].status = (1 ? true : false) as int)as bool)
but there seems to be a problem with this conversion. I am not getting exact way of converting int to bool in dart. It says
Conditions must have a static type of 'bool'.
To convert int to bool in Dart, you can use ternary operator :
myInt == 0 ? false : true;
To convert bool to int in Dart, you can use ternary operator :
myBool ? 1 : 0;
There is no way to automatically "convert" an integer to a boolean.
Dart objects have a type, and converting them to a different type would mean changing which object they are, and that's something the language have chosen not to do for you.
The condition needs to be a boolean, and an integer is-not a boolean.
Dart has very few ways to do implicit conversion between things of different type. The only real example is converting a callable object to a function (by tearing off the call method), which is done implicitly if the context requires a function.
(Arguably an integer literal in a double context is "converted to double", but there is never an integer value there. It's parsed as a double.)
So, if you have an integer and want a bool, you need to write the conversion yourself.
Let's assume you want zero to be false and non-zero to be true. Then all you have to do is write myInteger != 0, or in this case:
value: widget.studentDetailsList[index].status != 0
Try using a getter.
bool get status {
if(widget.studentDetailsList[index].status == 0)
return false;
return true;
}
Then pass status to value.
value: status
I know this is an old question, but I think this is a clean way to convert from int to bool:
myBool = myInt.isOdd;
Or with null safety
myBool = myInt?.isOdd ?? false;
Try this:
value: widget.studentDetailsList[index].status == 1
I've just published a lib to convert any object to a bool value in dart, asbool (Disclaimer: I'm the author)
For int objects you can use it as a extension (.asBool) or helper method (asBool(obj)):
int? num = 23;
int? num2;
assert(num.asBool == true); // true == true
assert(asBool(num) == true); // true == true
assert(num2.asBool == false); // false == false
assert(0.asBool == asBool(null)); // false == false
assert(120.asBool == asBool(2.567)); // false == false
It also works for whatever other object like Strings, Iterables, Maps, etc.
I like to assign the return value of a function to a variable, but inline. The following is how you would do it not inline.
bool isValid() {
if(a == b) return true;
if(a == c) return true;
return false;
}
bool result = isValid();
What I want is something like
bool result = () {
if(a == b) return true;
if(a == c) return true;
return false;
}
However it displays the error
The argument type 'Null Function()' can't be assigned to the parameter type 'bool'
How do I achieve this?
You are defining a lambda expression. This works the same way as in Javascript, Typescript or many other languages.
bool result = () {
if(a == b) return true;
if(a == c) return true;
return false;
}
This code defines an anonymous function of type () -> bool (accepts no parameters and returns bool). And the actual type of the result variable is bool so the compilation is broken (() -> bool and bool are non-matching types).
To make it correct just call the function to get the result.
bool result = () {
if(a == b) return true;
if(a == c) return true;
return false;
}();
Now you define an anonymous function (lambda) and then call it so the result is bool. Types are matching and there's no error.
This is rather an uncommon behaviour to define the function and immediately call it. It's used in Javascript to create a separate scope for variables using closures (some kind of private variables). I would recommend you to move the code to some kind of class or pass a, b, c parameters directly to the function:
bool isValid(a, b, c) {
/* Your code */
}
It's more generic that way and could be reused. Immediately called lambda is often a sign of bad design.