Flutter Dart convert nullable int? to nullable String? - flutter

I must pass int? parameter to method where I can use only String? parameter. How to do it shorter?
void mymethod(String? s)
{
print(s ?? "Empty");
}
int? a = null;
mymethod(a == null ? null : a.toString()); // how do this line easier?
Edit: I can't change parameter mymethod(String? s) to mymethod(int? s) - it still must be String?

I don't know if I understood correctly, but you want this ?
void mymethod(String? s)
{
print(s ?? "Empty");
}
int? a; // this could be null already
mymethod(a?.toString()); // "a" could be null, so if it is null it will be set, otherwise it will be set to String

You could just do this:
mymethod(a?.toString());
But if you want to make the check, my suggestion is to make the function do it.
int? a;
mymethod(a);
void mymethod(int? s) {
String text = "Empty";
if (s != null) text = s.toString();
print(text);
}

literally shorter, "" with $can help, with more complex you need use ${} instead of $.
Example: mymethod(a == null ? null : "$a");
Or you can create an extensiton on Int? and just call extension function to transform to String?, short, easy and reuseable. you can write the extension code elsewhere and import it where you need it.

Try with the following:
void mymethod(int? s) {
return s?.toString;
}
int? a = null;
mymethod(a);

Related

Avoid duplication of null type checking in Dart

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.

Flutter/Dart: Why does this statement effect null-nafety?

I realized this is just fine:
List<int> list = [];
int? b;
void addBarIfNull() {
if (b != null) {
list.add(b); // no problem
}
}
But adding this one statement b = null after adding b to the list, lets the linter complain with: The argument type 'int?' can't be assigned to the parameter type 'int':
List<int> list = [];
int? b;
void addBarIfNull() {
if (b != null) {
list.add(b); // problem: The argument type 'int?' can't be assigned to the parameter type 'int'
b = null;
}
}
Can someone explain what is going on here? Why is b considered as int? in list.add(b) if we clearly check before that it is not null? Why do both code snippets differ in handling this?
It is null safey issue when you declare
{
int? b;
}
you allow b to be null or have value but when you try to add
{
list.add(b);
}
b to the list you don't allow the list to contain null value that why the error message said you can't add int? to int you need to allow the list to contain null value if that whta you needed.
{
List<int?> list =[];
}

The return type 'int' isn't a 'String?', as required by the closure's context

what is the problem when I convert the string type value into an int so it will give me the following error mentioned in question.
If I understand your question correctly, you need to turn a String to int?
To do that, use int.parse(yourString) -> you will get int
If you are getting error with int and int? or String and String? (the same type but with question mark), try to use ?? operant
For example (with string value):
MyObject(
stringField: myString ?? '', //you are ensuring that if your String is null, there will be no error
);
if you want to return a String type data from int data, you need to convert it.
String test() {
int num = 0;
return(num.toString());
}
But if you want to return a int type data from String data, you need to parse it first to int.
int test() {
String pi = '3';
int now = int.parse(pi); // result from change String to int
return now;
}

How do I check if a value is a number (even or odd) with type double in Dart?

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;
}

casting int to bool in dart

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.