Skip inserting data in the list - flutter

I've got getter which gets list of my FilterModelRow. If condition is null I want to skip inserting the data into the list and the best do it inline
get getFilterRows {
return [FilterRowModel(Icon(Icons.title), 'Age', 'equal', age),
FilterRowModel(Icon(Icons.title), 'Age', 'min', minAge),
FilterRowModel(Icon(Icons.title), 'Age', 'max', maxAge)
];
}
I tried
...
age != null FilterRowModel(Icon(Icons.title), 'Age', 'equal', age): null
...
But that insert null which ends with an error. So how to completely skip adding line into the list if condition is met
Simplified version
var age = null;
List<int> myList = [age!=null ? age : null];
print(myList); //--> return [null] and I want to return empty list []

If you tell to your list to insert a null value, it will.
Now you have two options :
1 - You can instantiate your list and add values that are not null
List<int> myList = [];
if (age != null) myList.add(age);
2 - You can remove null values from your list with removeWhere method
myList.removeWhere((value) => value == null);

Related

Removing elements from a list where several nested values are null or empty in dart and flutter

I want to get my contacts from my phone and save them into firebase. The following code works if all I wanted to do is save the contact name, mainly because the name cannot be empty in the phone but a problem arises when the nested value
contact.phones is null or empty (shown below as "//works if I remove this").
Currently, if the phone field is empty, it throws a "StateError (Bad state: No element)" error.
Also, note that contacts.phone (result.phones after the attempt to remove the elements) is a list so I need to grab the first one.
I have tried to remove those elements from the list but that also sufferers from the same problem, the code to remove the empty phone fields fails for the same reason on this line.
if (!["", null, false, 0].contains(contact.phones?.first))
What is the correct way to remove elements from a list where the nested element is null or empty?
import '../../backend/backend.dart';
import '../../flutter_flow/flutter_flow_theme.dart';
import '../../flutter_flow/flutter_flow_util.dart';
import 'index.dart'; // Imports other custom actions
import 'package:flutter/material.dart';
import 'package:contacts_service/contacts_service.dart';
Future syncContactstoFirebase(String? userID) async {
List<Contact> contacts = await ContactsService.getContacts();
List result = [];
for (var contact in contacts) {
if (!["", null, false, 0].contains(contact.phones?.first)) {
result.add(contact);
}
}
final instance = FirebaseFirestore.instance;
CollectionReference collection =
instance.collection('users').doc(userID).collection('contacts');
late Map<String, dynamic> data;
if (result != null)
data = {
'contacts': contacts
.map((k) => {
'name ': k.displayName,
'phone': k.phones?.first.value //works if I remove this
.toString()
.replaceAll(new RegExp(r"\s\b|\b\s"), "")
.replaceAll(new RegExp(r'[^\w\s]+'), '')
})
.toList(),
};
return collection
.doc()
.set(data)
.then((value) => print("Contacts Updated"))
.catchError((error) => print("Failed to update Contacts: $error"));
}
EDIT: See note below.
Is there a way to handle more than one nested element so for instance the mapping code becomes:-
if (result != null)
data = {
'contacts': contacts
.map((k) => {
'name ': k.displayName,
'phone': k.phones?.first.value,
'email': k.email?.value ///////ADDED THIS////////
.toString()
.replaceAll(new RegExp(r"\s\b|\b\s"), "")
.replaceAll(new RegExp(r'[^\w\s]+'), '')
})
.toList(),
};
I'm not entirely sure, but I believe you would want to replace it with
if (!["", null, false, 0].contains(contact.phones?.firstOrNull))
To use firstOrNull you need
import 'package:collection/collection.dart';
When you want to remove a specific group of elements from a list that satisfy a condition, you can use the removeWhere function on your list.
So, in your example, if you want to remove all contacts with null or empty phones from your contacts list, the bellow line of code should do the trick:
contacts.removeWhere(
(element) => element.phones == null || element.phones!.isEmpty);
if you want to remove the contacts that don't have phone number and email you can change the condition of the removeWhere like this:
contacts.removeWhere(
(element) => (element.phones == null || element.phones!.isEmpty) && (element.emails == null || element.emails!.isEmpty));
You can basically add any condition and remove the elements that satisfy that condition
So simple when I got the syntax right, particularly the use of ! and ? in null safety. An if clause, before it adds the element in the mapping, is what does the trick.
if (contacts != null)
data = {
'contacts': contacts
.map((k) => {
if (k.displayName!.isNotEmpty && k.displayName !=null) 'name': k.displayName,
if (k.emails!.isNotEmpty && k.emails != null) 'email': k.emails?.first.value,
if (k.phones!.isNotEmpty && k.phones != null) 'phone': k.phones?.first.value
.toString()
.replaceAll(new RegExp(r"\s\b|\b\s"), "")
.replaceAll(new RegExp(r'[^\w\s]+'), '')
.replaceAll(new RegExp(r'/^(?!\s*$).+/'), '')
})
.toList(),
};

How to sort a list that could contain null values with dart null-safety

I have a list of strings that may contain null values, how do I sort this list?
I'm using Flutter beta channel so null-safety is checked. This is what I have so far:
List<String?> _list = [
'beta',
'fotxtrot',
'alpha',
null,
null,
'delta',
];
_list.sort((a, b) => a!.compareTo(b!));
How do I get this as the outcome:
_list = [
null,
null,
'alpha',
'beta',
'delta',
'fotxtrot',
];
I encountered this recently and built a one line function based on compareTo documentation:
myList.sort((a, b) => a==null ? 1: b==null? -1 : a.compareTo(b));
NB: This brings the null value at the end of the list. In your case just swap -1 and 1 to have them at the front of your List.
You need to modify your sorting method to handle nullable values, not just ignore them. After handling potential nulls you can compare them normally.
_list.sort((a, b) {
if(a == null) {
return -1;
}
if(b == null) {
return 1;
}
return a.compareTo(b);
});
You could also use whereType:
List<String?> _list = [
'c',
'a',
'd',
null,
null,
'b',
];
void main() {
var list = _list.whereType<String>().toList();
list.sort();
print(list); // [a, b, c, d]
}

EF Core Select query with null references

I have a Select query that performs a check on a child navigation property to then check another referenced property. The first child navigation property can be null but the second property isRequired() and if the first child is not null in the database, the query runs fine but if one or more rows exist that do not have a referencing value for that property then I get -
An exception occurred while iterating over the results of a query
for...
How can I make a query with an optional property run and return null for the records that have no references.
await _dbContext.NewsBoard
.AsNoTracking()
.Select(item => new NewsResponse
{
Id = item.BoardId,
MediaType = new MediaTypeResponse
{
Id = item.Media.MediaTypeId,
Name = item.Media.MediaType.Name
},
Above is the query I am trying to run, the item.Media does not exist have a value for its foreign key (its null) and so the expected result would have been a list of NewsResponse with MediaType being null where there is a null referenced item.Media.
Use a null check in your query like -
await _dbContext.NewsBoard
.AsNoTracking()
.Select(item => new NewsResponse
{
Id = item.BoardId,
MediaType = item.Media == null ? null : new MediaTypeResponse // null check
{
Id = item.Media.MediaTypeId,
Name = item.Media.MediaType.Name
}
})
.ToList();

Can't create a condition for null values in an array?

I am using linq expression trees to build a query.
My array:
string[] { null, null }
condition I want to implement:
x == null ? null : x.ToLower()
My linq expression looks like this:
{Param_0 => value(System.String[]).Any(Param_1 => (Param_0.FirstName.ToLower() == IIF((Param_1 == null), null, Param_1.ToLower())))}
This is my first attempt and I can't seem to find the correct way to do it
Constant = Expression.Condition(Expression.Equal(Constant, Expression.Constant(null, typeof(string))), Expression.Constant(null, typeof(string)), Expression.Call(Constant, "ToLower", null));
The expected result is to be able to call .ToLower() on elements that are not null
It seems to me that you want an expression that represents a function call with input a string, and output a string.
Expression<Func<string, string>>
How about a Lambda expression?
Expression<Func<string, string>> myExpression = (x) => (x==null) ? null : x.ToLower();
This expression can be used in a Queryable Select statement, like below:
IQueryable<string> myItems = new List<sring>()
{
"Abc",
null,
"DEF",
null,
"gHI",
}
.AsQueryable();
IQueryable<string> myLowerCaseItems = myItems.Select(myExpression);
foreach (string item in myLowerCaseItems)
{
if (item == null)
Console.WriteLine("<null>");
else
Console.WriteLine(item);
}
This yields the following output:
abc
def
ghi

Filter condition not working properly on list (C#3.0)

I have a datatable that has many NULL or " " strings. Next I am type casting the DataTable to a list .
Now if I want to filter those conditions on this list and get the resultant value(without NULL or String.Empty or " " records) what should I do?
My code
DataTableExtensions.AsEnumerable(dt).ToList().ForEach(i =>
{
if (i[0] != null)
{
if ((i[0].ToString() != string.Empty)|| (i[0].ToString() != " "))
{
list = dt.AsEnumerable().ToList();
}
}
});
But I am getting all the records. It is not getting filtered.
Using C#3.0
Please help
Thanks
You're looking at i[0] so I'm going to assume that you're only interested in the first column of your table:
var rows = dt.AsEnumerable()
.Where(r => !r.IsNull(0) // check for DBNull
&& r[0] != null
&& r[0].ToString().Trim().Length > 0)
.ToList();
So that looks at every row but only returns the rows where the first column has a value and the string value is not empty or whitespace.