Problem: While I was implementing REST API, I came across some conditional displays of widgets. So the API response back with a bool value. Now if the bool value is false then I want to show a TextField Widget in the UI else Just a Text Widget. Now I am confused as to how exactly I should implement it.
Here's how API functions We would send a post request with an email in their body. And the API would check whether the API is present in their database and in return they will send true false and response.
I will be herewith attaching my code snippets.
API Manager
class ApiService {
static const int TIME_CONST = 20;
Future<UserCheck> apiUserCheck(dynamic param) async {
var client = http.Client();
try {
var response = await client
.post(
Uri.https(
"baseUrl", "endpoint"),
body: param)
.timeout(Duration(seconds: TIME_CONST));
if (response.statusCode == 200) {
print('Response Body: ${response.body}');
final data = jsonDecode(response.body);
return UserCheck(
user: data['user_exists'],
);
} else {
print("The response status is not 200");
return param;
}
} on SocketException {
throw FetchDataException('message', 'url');
} on TimeoutException {
throw ApiNotRespondingException("message", "url");
}
}
}
class UserCheck {
final bool? user;
UserCheck({this.user});
}
Function Used in the UI file
checkUserExist() {
final check = ApiService();
check.apiUserCheck({
"email": emailController.text,
}).then((value) {
if (value.user == true) {
print('User Exist: ');
} else {
print('User Does Not exists');
}
});
}
UI Part:
Padding(
padding: EdgeInsets.fromLTRB(15, 20, 15, 5),
child: TextField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
),
),
),
////////IF ELSE BLOCK TO BE USED HERE TO DISPLAY COMDITIONAL WIDGETS/////
SizedBox(
height: 50.h,
),
Note: The implementation of the API works very well and I could validate whether an email is present or not. I am receiving the response body as true and false.
Thanks in advance.