Dart using Null safe for variables - flutter

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

Related

Flutter Map or .fromJson of my not working

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.

RangeError (index): Invalid value: Not in inclusive range 0..2: 3 i cant fix

i have a problem this my list
class _FitnessAppState extends State<FitnessApp> {
String img_Header =
"https://images.unsplash.com/photo-1517836357463-d25dfeac3438?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80";
List trainingImage = [
"https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1631&q=80",
"https://images.unsplash.com/photo-1575052814086-f385e2e2ad1b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",
"https://media.istockphoto.com/photos/picture-of-people-running-on-treadmill-in-gym-picture-id879180126?k=20&m=879180126&s=612x612&w=0&h=WZ1Iqcqv5_rNTNslUscoMg9qAUoNiDG8kWBfVnpPapQ=",
];
your variables are:
String img_Header = "https://images.unsplash.com/photo-1517836357463-d25dfeac3438?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80";
List trainingImage = [
"https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1631&q=80",
"https://images.unsplash.com/photo-1575052814086-f385e2e2ad1b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",
"https://media.istockphoto.com/photos/picture-of-people-running-on-treadmill-in-gym-picture-id879180126?k=20&m=879180126&s=612x612&w=0&h=WZ1Iqcqv5_rNTNslUscoMg9qAUoNiDG8kWBfVnpPapQ=",
];
the error of RangeError is happened in trainingImage variable as it is a List datatype, that's because you are trying to access an unavailable index inside a List, as example, your list trainingImage has only 3 elements which start by index 0 and ends by index 2:
print(trainingImage[0]);
// output: "https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1631&q=80"
print(trainingImage[1]);
// output: "https://images.unsplash.com/photo-1575052814086-f385e2e2ad1b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80"
print(trainingImage[2]);
// output: "https://media.istockphoto.com/photos/picture-of-people-running-on-treadmill-in-gym-picture-id879180126?k=20&m=879180126&s=612x612&w=0&h=WZ1Iqcqv5_rNTNslUscoMg9qAUoNiDG8kWBfVnpPapQ="
if you are trying to access the index 3 you will get the error of RangeError:
print(trainingImage[3]);
// output: RangeError (index): Invalid value: Not in inclusive range 0..2: 3
the solution is to always check if an index is available before accessing it:
// as example you want to access the index 3
int index = 3;
// 1st way
if(trainingImage.asMap().containsKey(index))
{
// run this if index 3 is available
}
// 2nd way
if(index < trainingImage.length && index >= 0)
{
// run this if index 3 is available
}
The code snippet that you have provided is fine. Maybe you are accessing wrong index of the list. Can you provide more information please?
However, I'll suggest you to rename the img_Header variable to imgHeader otherwise it will show lowerCamelCase warning.

How to avoid that 0 (zero) int turns into Postgres "null" value and violates "not null" constraint?

In Go, I am unmarshalling/decoding JSON into a struct with an ID field of type int. Then I try to insert this struct into a PostgreSQL database using go-pg with the ID column as the primary key (which has a not-null constraint). The first entry has a 0 as its ID. In the Postgres documentation, it states that 0 is ok as a value of a primary key. However, I keep getting an error message:
"ERROR #23502 null value in column "number" violates not-null constraint".
It looks like the 0 turns into a Go "zero value" when it is unmarshalled into the int value. Then it is inserted as null value into Postgres. Any tips on how I might be able to avoid this would be greatly appreciated.
type Account struct {
Number int `sql:"type:smallint, pk"`
Name string
}
[...]
account := Account{}
err := json.NewDecoder(r.Body).Decode(&account)
[...]
insertErr := pgLayer.db.Insert(&account)
if insertErr != nil {
log.Printf("Error while inserting new item")
return "n/a", insertErr
}
While it's not immediately obvious with go-pg you can use the struct tag sql:",notnull" to show that Go empty values ("", 0, [] etc.) are allowed and should not be treated as SQL NULL.
You can see it in the Features list.
In your case I would change this to:
type Account struct {
Number int `sql:"type:smallint,pk,notnull"`
Name string
}
I think the easiest solution to your problem is to make your ID column of type SERIAL and let Postgres deal with setting and auto-incrementing the value for you. If you need the value within your application directly after inserting it, you can always use a RETURNING psql clause, like such:
INSERT INTO shows(
user_id, name, description, created, modified
) VALUES(
:user_id, :name, :created, :modified
) RETURNING id;
And capture the response within your code.

Default value for null fields in a Jasper Report

Background
A ResultSet has many Double value fields (with patterns like "###0.000"). Some values can be null.
Problem
I want to replace null values with "N/A", which is a String and cannot print to a Double field. Printing "0.00" for null values is unacceptable.
Using an PrintWhenExpression value of ($F{value} != null) ? $F{value} : "N/A" does not work; it is not possible to use patterns in that way.
Idea
Add hidden fields that write "N/A". These fields will be printed only if value is null.
Question
Is there a better solution, and if so, what is it?
Thank you.
Solution #1
Your solution:
Use a regular Double field (doubleField) for the column value.
Add a static String text field at the same location.
Change the Double field to Blank When Null.
Set the PrintWhenExpression value for the String text field to: $F{doubleField} == null.
Solution #2
The problem is, as you pointed out, that a Double and a String are two different data types. You can assign a String variable to the value of the Double using an appropriate expression. Then use the String variable as the field. The expression might resemble:
($F{doubleField} == null) ?
"N/A" : new java.text.DecimalFormat("#.##").format($F{doubleField})
(Note: My preference is to use == instead of !=. Think positive.)
Solution #3
Change the SQL statement to pre-format the Double as a text string, and use the "N/A" in the string (by using a CASE or DECODE statement in the query).
Avoid this solution, though, as it is not maintainable.
Recommendation
Do not hard-code the "N/A" string throughout the report(s); put the "N/A" text in a constant, or a parameter with a default value of "N/A".
You can try something like this in your field expression:
("Your static text "+(($F{field}!=null)?$F{field}:""))
Or, if you don't want your static text to be visible when the field is null, try putting $F{field}!=null in your PrintWhenExpression.

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.