I am facing Null check operator used on a null value
error when loading the profile page.
In profile page I call the profile details API first and from that I am showing the details like name, email, username and phone number on the UI. When loading the API I will get this error and after API load this error will vanished. I added a null check but that doesn't solve my problem.
My Code:
class _UserDetailsState extends State<UserDetails> {
ProfileResponse? profileResponse;
//created variables
String phoneNumber = "";
String fullName = "";
String email = "";
String username = "";
Future<void> fetchData() async {
try {
final response = await getProfileDetails();
if (response?.statusCode == 200) {
Map<String, dynamic> parsedData = jsonDecode(response!.body);
setState(() {
profileResponse = ProfileResponse.fromJson(parsedData);
//null check added here
if (profileResponse?.phoneList.length != 0) {
phoneNumber = profileResponse!.phoneList[0].phoneNumber;
}
else {
phoneNumber = "";
}
if(profileResponse?.userTO?.firstName != null){
fullName = profileResponse!.userTO!.firstName;
}
else{
fullName = "";
}
if(profileResponse?.userTO?.lastName != null){
fullName = fullName + " "+ profileResponse!.userTO!.lastName;
}
if(profileResponse?.userTO?.username != null){
username = profileResponse!.userTO!.username;
}
else{
username = "";
}
if(profileResponse?.userTO?.email != null){
email = profileResponse!.userTO!.email;
}
else{
email = "";
}
});
} else {
//message
}
} catch (error) {
//message
}
}
@override
void initState() {
fetchData();
}
Future<http.Response?> getProfileDetails() async {
final String url = "API CALL";
final response = await http.get(Uri.parse(url));
return response;
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Container(
child: TextField(
controller: new TextEditingController.fromValue(
new TextEditingValue(
text: fullName, //value setting
selection:
new TextSelection.collapsed(
offset: profileResponse!.userTO!.firstName.length))),
),
Container(
child: TextField(
controller: new TextEditingController.fromValue(
new TextEditingValue(
text: username, //value setting
selection:
new TextSelection.collapsed(
offset: profileResponse!.userTO!.username.length))),
),
Container(
child: TextField(
controller: new TextEditingController.fromValue(
new TextEditingValue(
text: email, //value setting
selection:
new TextSelection.collapsed(
offset: profileResponse!.userTO!.email.length))),
),
Container(
margin: const EdgeInsets.only(bottom: 16),
child: TextField(
controller: new TextEditingController.fromValue(
new TextEditingValue(
text: phoneNumber, //value setting
selection:
new TextSelection.collapsed(offset: phoneNumber.length))),
],
),
);
}
}