Flutter Map or .fromJson of my not working - flutter

I have data response with api and i can't map it to List but it return users null, i think is not working because method fromJson
this is data return with api
and this is my models
My controller
end is Debug window
Thanks for any answer

Could you further specify what it is that you get as a result? Is the whole list full of null? Or are some of the objects' fields null?
Here is what I believe is an error:
nameUser: json['tenNguoiDung'] == null ? '' : json['ten']
avatarUser: json['nguoiDung_anhDinhKem'] == null ? '' : json['avatar'],
You are saying:
If tenNguoiDung is null: nameUser is equal to '', if it isn't, nameUser = json['ten'].
But your json doesn't have a 'ten' field, so it will be null. What you are most likely looking for is the if-null operator:
nameUser: json['tenNguoiDung'] ?? ''
avatarUser: json['nguoiDung_anhDinhKem'] ?? ''
which will assign '' if the json field is null.

Related

Initialize with flexible keys in fromJson

I want to set Movie/TV information values that fetch form API, but what some JSON keys are different, but values types are same the difference is not so much to create another model for that, so I want to continue with main model class.
For example title is key for movie but for TV is name key in JSON, and some other keys that are different.
I've tried to solve it with checking, but it did not work:
final String? title;
factory Result.fromJson(Map<String, dynamic> json) => Result(
title: json["title"] == Null ? json["name"] : json["title"],
...
)
As I mentioned that work for Movie but for TV will not work, error that shows for that:
Unhandled Exception: type 'Null' is not a subtype of type 'String'
I also tried this method, but it didn't work for both parts as before:
title: json["name"] ?? json["title"]
How can I handle initialization with flexible keys?
Null is not string type, you can check with null
json["title"] == null ? json["name"] : json["title"],

Dart using Null safe for variables

in this below code _invoiceInformation in first initialize is null and i'm trying to use dart null safe to manage that in my flutter applications
in this code although i used ? operation i still get error:
Error:
RangeError (index): Index out of range: no indices are valid: 0
what i want to try:
_invoiceInformation = Hive.box<InvoiceInformation>('invoice_information');
_province.text=_invoiceInformation?.getAt(0)?.province??'';
_province.text=_invoiceInformation?.getAt(0)?.province??'';
If the list _invoiceInformation is empty i.e having zero elements, then the null aware operator ? will allow you to access the element at 0, which is causing the error.
You will also have to check whether the list is empty or not before accessing its elements.
if(_invoiceInformation != null && _invoiceInformation.isNotEmpty) {
_province.text=_invoiceInformation.getAt(0)?.province ?? '';
}

Handle null value in Dart / Flutter

I have this User class and then a Firestore Document, that may or may not contain a photoURL or some other values. The problem is, that when I try to create an user I get this exception because some of the values are Null.
I've tried to handle it like this:
var photoURL = snapshot.data['photoURL'] ??= '';
but it seems it doesn't work.
Can anyone explain best practices handling Null values in Dart/Flutter respectively?
EDIT: I'm checking if snapshot.exists before and if I create the user omitting the values I know are Null, it creates it properly.
EDIT 2: I've found the problem appears when I try to handle empty List like this:
var favorites = snapshot.data['favorites'] ?? [''];
It seems I was initialized the value the wrong way when I converted it to Json.
I handle the empty Array like this
Map<String, dynamic> toJson() => {
'favorites' : favorites ?? '',
}
when it should be:
Map<String, dynamic> toJson() => {
'favorites' : favorites ?? [''],
}
So it was throwing when I tried to assign an empty Array to String.

JPQL: How to write dynamic where conditions

I am struggling with JPQL dynamic where condition. I tried searching the syntax for the same but coluldn't find one.
in my case if user is passing the name parameter then the select query should be
select * from user where name = 'sanjay'
if user is not passing name parameter then select query should be
select * from user
Below is my jpql query format which fails when name parameter is not passed.
entity_manager.createQuery("select u from user u where u.name = :name").setParameter("name",params[:name]).getResultList()
How can i update above JPQL query to support both the cases i.e when the name parameter is passed and when the name parameter is not passed ??
This is not possible in JPQL. You even cannot do something like
createQuery("select u from user u where u.name = :name OR :name IS NULL")
It is not possible. That simple. Use two queries or use the Criteria API.
This is the answer I get when I tries to do like you it is working with some modification.
In my case I had the problem that my optional parameter was a List<String> and the solution was the following:
#Query(value = "SELECT *
FROM ...
WHERE (COLUMN_X IN :categories OR COALESCE(:categories, null) IS NULL)"
, nativeQuery = true)
List<Archive> findByCustomCriteria1(#Param("categories") List<String> categories);
This way:
If the parameter has one or more values it is selected by the left side of the OR operator
If the parameter categories is null, meaning that i have to select all values for COLUMN_X, will always return TRUE by the right side of the OR operator
Why COALESCE and why a null value inside of it?
Let's explore the WHERE clause in all conditions:
Case 1: categories = null
(COLUMN_X IN null OR COALESCE(null, null) IS NULL)
The left part of the OR will return false, while the right part of the OR will always return true, in fact COALESCE will return the first non-null value if present and returns null if all arguments are null.
Case 2: categories = ()
(COLUMN_X IN null OR COALESCE(null, null) IS NULL)
JPA will automatically identify an empty list as a null value, hence same result of Case 1.
Case 3: categories = ('ONE_VALUE')
(COLUMN_X IN ('ONE_VALUE') OR COALESCE('ONE_VALUE', null) IS NULL)
The left part of the OR will return true only for those values for which COLUMN_X = 'ONE_VALUE' while the right part of the OR will never return true, because it is equals to 'ONE_VALUE' IS NULL (that is false).
Why the null as second parameter? Well, that's because COALESCE needs at least two parameters.
Case 4: categories = ('ONE_VALUE', 'TWO_VALUE')
(COLUMN_X IN ('ONE_VALUE', 'TWO_VALUE') OR COALESCE('ONE_VALUE', 'TWO_VALUE', null) IS NULL)
As in Case 3, the left part of the OR operator will select only the rows for which COLUMN_X is equale to 'ONE_VALUE' or 'TWO_VALUE'.

EntLib Way to Bind "Null" Value to Parameter

I wish to pass Null Value to the parameter as follow:
_db.AddInParameter(dbCommand, "Id", DBNull.Value, myContactPerson.Id);
I am receiving the following error :
"can not convert "System.DBNull to System.Data.DbType".
I know the meaning of this error.
But i need to supply null value to myContactPerson.Id
How can i achieve this ?
If myContactPerson.Id isn't an auto-number, then why not just pass 0.
DBType should be passed in that parameter and should match your the dbtype (string, int, etc.) for the table that you are comparing with in your database. You would replace your value field "myContactPerson.Id" with DBNull.Value to always pass the null value.