1

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.

Pratyay Sinha
  • 511
  • 1
  • 6
  • 16

2 Answers2

3

You should be using visibility widget.

According to docs

Whether to show or hide a child.

By default, the visible property controls whether the child is included in the subtree or not; when it is not visible, the replacement child (typically a zero-sized box) is included instead.

You can do something like this

           Visibility(child:
           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/////
              replacement:
              SizedBox(
                height: 50.h,
              ),
              visible: //your if condition
        ),
Rahul
  • 4,699
  • 5
  • 26
  • 38
0

You could try this FutureBuilder example:

Widget build() {
  return FutureBuilder<bool>(
    future: checkUserExist(),
    builder: (context, snapshot) {
      if(snapshot.hasData) {
         if(snapshot.data) {
           return TextField();
         } else {
           return Text();
         }
       } else {
       /// Do something if there is no data like loading...
}
      
    }
  );
}

Also change the checkUserExistfunction:

Future<bool> checkUserExist() async {
        final check = ApiService();
        return await check.apiUserCheck({
          "email": emailController.text,
        });
      }
NelsonThiago
  • 802
  • 7
  • 12