【问题标题】:Show a different widget when the bool value is true and false in Flutter在 Flutter 中当 bool 值为 true 和 false 时显示不同的小部件
【发布时间】:2021-09-30 02:31:04
【问题描述】:

问题:在实现 REST API 时,我遇到了一些小部件的条件显示。 所以 API 响应返回一个 bool 值。现在,如果 bool 值为 false,那么我想在 UI 中显示一个 TextField 小部件,否则只是一个文本小部件。 现在我很困惑我应该如何实现它。

API 的功能如下 我们会在他们的正文中发送带有电子邮件的发布请求。 API 会检查 API 是否存在于他们的数据库中,作为回报,他们会发送 true false 和响应。

我将附上我的代码 sn-ps。

API 管理器

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});
}

UI 文件中使用的函数

        checkUserExist() {
        final check = ApiService();
        check.apiUserCheck({
          "email": emailController.text,
        }).then((value) {
          if (value.user == true) {
            print('User Exist: ');
          } else {
            print('User Does Not exists');
          }
        });
      }

用户界面部分:

 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,
              ),

注意:API 的实现运行良好,我可以验证电子邮件是否存在。我收到的响应正文是真假。

提前致谢。

【问题讨论】:

    标签: flutter dart if-statement flutter-widget flutter-container


    【解决方案1】:

    您应该使用可见性小部件。

    根据文档

    是显示还是隐藏孩子。

    默认情况下,visible 属性控制孩子是否是 是否包含在子树中;当它不可见时, 而是包含替换子项(通常是一个零大小的框)。

    你可以这样做

               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
            ),
    

    【讨论】:

      【解决方案2】:

      你可以试试这个FutureBuilder 例子:

      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...
      }
            
          }
        );
      }
      

      同时更改checkUserExist函数:

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

      【讨论】:

      • 嘿@NelsonThiago 不,这里没有数据流动。 API 只是返回一个真或假。因此,根据 API 返回的内容,我需要显示小部件
      • 是的,如果用户存在与否,这就是您设置条件以显示不同小部件的方式。
      • 或者您在检查流程和小部件更改方面需要帮助吗?
      • 然后我将添加我的 API 服务类
      • 是的,我在检查流程方面需要帮助。
      猜你喜欢
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 2020-10-16
      • 2017-05-19
      相关资源
      最近更新 更多