I want to call the data from API using horizontal_data_table on flutter. this is the code where it gets the error
Container(
width: 200,
height: 52,
padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
alignment: Alignment.centerLeft,
child: Text(widget.leavelistmodel.response[index].paidLeaveEmployeeNip),
),
and the data model from the result looks like this:
class LeaveListResult {
int? paidLeaveId;
String? paidLeaveEmployeeNip;
String? paidLeaveEmployeeFullName;
}
I'm already changing it into? and ! it still got an error, how can I fix the error?
CodePudding user response:
We used nullSafty
for the model variable. ?
class LeaveListResult {
int? paidLeaveId;
String? paidLeaveEmployeeNip;
String? paidLeaveEmployeeFullName;
}
Since it is the same as Swift's optional, nullSafty must be canceled.
Container(
width: 200,
height: 52,
padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
alignment: Alignment.centerLeft,
child: Text(widget.leavelistmodel.response[index].paidLeaveEmployeeNip ?? 'NULL'),
),
You can force unwrapping with !
, but this is not a good practice. The reason is that an error occurs when it is null. When it is null by using channing
, an exception handling message should be displayed instead of an error.
CodePudding user response:
the Text
can't accept a nullable String?
, if you're sure that your data isn't null
then do this:
child: Text(widget.leavelistmodel!.response[index]!.paidLeaveEmployeeNip),
you can also set a default value for the String?
that will be shown when it's null
:
child: Text(widget.leavelistmodel?.response[index]?.paidLeaveEmployeeNip ?? "default value"),
CodePudding user response:
The response
can be null on this case. You can check the null value and then move forward. As for paidLeaveEmployeeNip
filed also a nullable String but Text widget doesnt accept null value. You can directly accept null string
child: Text("${widget.leavelistmodel.response?[index].paidLeaveEmployeeNip}"),
Or for default value
Text(widget.leavelistmodel.response?[index].paidLeaveEmployeeNip ?? "Got Null")