I am still coming up to speed with dart and wanted to know if there was an easier way to not execute a statement if the value is null. See example below:
I can always do the if statements below for setting field3 and field4, but felt like something like field5 should work. But when I try to do that, it complains that a null check operator is used on a null value.
Also I don't want to change the Map to have a dynamic value.
Is there a single one liner to do what I am trying to do, or do I just need to check for null before setting the value.
Map<String, Object> myMap = {};
print('running now');
try {
myMap['field1'] = DummyClass.getString('hello');
myMap['field2'] = DummyClass.getString('good');
//Is there a more concise way to do this than the 2 options below?
if (DummyClass.getOptionalString('goodbye') != null) {
myMap['field3'] = DummyClass.getOptionalString('goodbye')!;
}
String? temp = DummyClass.getOptionalString('go');
if (temp != null) {
myMap['field4'] = temp;
}
// This gives an error 'null check operator used on a null value'
// myMap['field5'] ??= DummyClass.getOptionalString('to')!;
} catch (e) {
print('error condition, $e');
}
print(myMap);
}
class DummyClass {
static String getString(String? strParam) {
String? retString = getOptionalString(strParam);
if (retString == null) {
throw ('nulls are not allowed');
}
return retString;
}
static String? getOptionalString(String? strParam) {
if (strParam == null || strParam.length < 3) {
return null;
}
return strParam;
}
}
There's no built-in way to do what you want, but you could write a function (or extension method) to do it. For example:
extension MapTrySet<K, V> on Map<K, V> {
void trySet(K key, V? value) {
if (value != null) {
this[key] = value;
}
}
}
and then you could do:
myMap.trySet('field3', DummyClass.getOptionalString('goodbye'));
myMap.trySet('field4', DummyClass.getOptionalString('go'));
Alternatively, if you really want to use normal Map syntax, you could create your own Map class that has a void operator []=(K key, V? value) override and does nothing when the value is null, but that probably would not be worth the effort.
The issue is that the ??= operator assigns to the left if it is null. Expanded, it would look something like this:
a ??= b;
// Equivalent to:
if (a == null) {
a = b;
}
Which is not something that you're trying to achieve. AFAIK, there is no such operator yet in Dart. However, you can try this:
final possiblyNullValue = '';
final myMap = <String, String>{};
myMap['key'] = possiblyNullValue ?? myMap['key'];
// Equivalent to:
if (possiblyNullValue != null) {
myMap['key'] = possiblyNullValue;
}
// or:
myMap['key'] = possiblyNullValue != null? possiblyNullValue : myMap['key'];
Which would work in your case as a one-liner.
You could create your map with all entries, even null, and then filter the null values out:
void main() {
try {
final myMap = <String, dynamic>{
'field1': DummyClass.getString('hello'),
'field2': DummyClass.getString('good'),
'field3': DummyClass.getOptionalString('goodbye'),
'field4': DummyClass.getOptionalString('go'),
}..removeWhere((k, v) => v == null);
print(myMap);
} catch (e) {
print('error condition, $e');
}
}
static Location fetchById(int id) {
List<Location> locations = Location.fetchAll();
for (var i = 0; i < locations.length; i++) {
if (locations[i].id == id) {
return locations[i];
}
}
return null;
}
// if the condition is not true then return null when I try to return null or false it gives the error 'A value of type 'Null' can't be returned from the method 'fetchById' because it has a return type of 'Location'.
With null-safety feature in the dart language, you have to explicitly tell if you want to make a value nullable.
Define the return type with a ?, so dart knows that return value can be null.
static Location? fetchById(int id)
{
/// function body
}
I am trying to check the name of a key in a list and then change the name if it meets a certain criteria.
My code so far is:
String convert(double key) {
if(key == '1') {
return "One";
} else if(key == '2') {
return "Two";
}
//This the the list loop:
for (var entry in optoins.entries) {
entry.key = convert(entry.key); //This seems to be incorrect
if (entry.key == "One") {
//do somehting
}
}
The error I get is this one:
The argument type 'String' can't be assigned to the parameter type 'double'.
I know I can do if (entry.key == "1") but later in the code I need entry.key to be a string One and not 1, so I would like to change the name before starting the if else check.
The problem is your code entry.key is a double variable and not a string. I would suggest adding a new field to the entry class called stringKey and store this value there. That would be something like
String convert(String key) {
if(key == '1') {
return "One";
} else if(key == '2') {
return "Two";
}
//This the the list loop:
for (var entry in optoins.entries) {
entry.stringKey= convert(str(entry.key)); //This seems to be incorrect
if (entry.stringKey== "One") {
//do somehting
}
}
I have bellow class :
public class KardeksKalaComplexColumnInfoM{
private decimal _Qty;
public decimal Qty
{
get { return _Qty; }
set
{
if (_Qty != value)
{
_Qty = value;
this.RaisePropertyChanged("Qty");
this.RaisePropertyChanged("Total");
}
}
}
private decimal _Fee;
public decimal Fee
{
get { return _Fee; }
set
{
if (_Fee != value)
{
_Fee = value;
this.RaisePropertyChanged("Fee");
this.RaisePropertyChanged("Total");
}
}
}
public decimal Total
{
get { return Qty * Fee; }
}
}
and a context contains buys and sales,i run bellow code and results commented in three last lines:
var q_buys = (
from
r_d in _db.BuyDetails
select new KardeksKalaDetailM()
{
ID = r_d.ID,
Date = r_d.Date,
in = new KardeksKalaComplexColumnInfoM() {Qty = r_d.Qty, Fee = r_d.Fee },
});
var q_sales = (
from
r_d in _db.SaleDetails
select new KardeksKalaDetailM()
{
ID = r_d.ID,
Date = r_d.Date,
in = new KardeksKalaComplexColumnInfoM() { Qty=0 , Fee=0 },
});
var q1=q_buys.ToList(); // Ok
var q2=q_sales.ToList(); // Ok
var result=q_buys.Concat(q_sales).ToList(); // Error
when I change the KardeksKalaComplexColumnInfoM filed types to double the last line's error solved but when them types are decimal it has bellow error:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The specified cast from a materialized 'System.Int32' type to the 'System.Int64' type is not valid.
how can resolve last line problem?
The Start_time field in Database table(dbo.QRTZ_TRIGGERS) shows this value 635371706123133677
What format is this and how can it be converted to human readable format
This is the from the StdAdoDelegate.cs class:
AddCommandParameter(cmd, "triggerStartTime", GetDbDateTimeValue(trigger.StartTimeUtc));
And GetDbTimeValue is
public virtual object GetDbDateTimeValue(DateTimeOffset? dateTimeValue)
{
if (dateTimeValue != null)
{
return dateTimeValue.Value.UtcTicks;
}
return null;
}
So basically DateTimeOffset.UtcTicks
And this is the code used to convert that value back:
public virtual DateTimeOffset? GetDateTimeFromDbValue(object columnValue)
{
if (columnValue != null && columnValue != DBNull.Value)
{
var ticks = Convert.ToInt64(columnValue, CultureInfo.CurrentCulture);
if (ticks > 0)
{
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
}
return null;
}