微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在值上使用 GetX?

如何解决如何在值上使用 GetX?

我想做一个Password TextField,其中的内容可见性可以通过后缀图标来控制。

代码可能是这样的:

import 'package:Flutter/material.dart';
import 'package:get/get.dart';

void main() {
  runApp(TestGetX());
}

class TestGetX extends StatelessWidget {
  var eyeClosed = true.obs;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Test GetX"),),body: Align(
          alignment: Alignment.center,child: Padding(
            padding: EdgeInsets.all(20),child: TextFormField(
              obscureText: eyeClosed.value,decoration: Inputdecoration(
                icon: Icon(
                  Icons.security,color: Colors.purple,hintText: "Your Password",hintStyle: TextStyle(color: Colors.grey),suffix: Obx(
                  () => InkWell(
                    child: eyeClosed.value
                        ? Icon(Icons.visibility_off,color: Colors.grey)
                        : Icon(Icons.visibility,color: Colors.purple),onTap: () {
                      eyeClosed.value = !eyeClosed.value;
                    },);
  }
}

后缀图标可以被 Obx() 控制,但是 obscureText 不起作用。直接的方法是在TextFormField上使用Obx(),但我认为这不是最好的方法

结果如下:

enter image description here

解决方法

当您的状态发生变化时,您应该使用 StatefulWidget。另外,您可以达到您想要的相同结果,而无需“获取”包。 我在这里给你举个例子:

import 'package:flutter/material.dart';

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
  bool hidePassword = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 15),child: TextFormField(
            obscureText: hidePassword,// which is true by default
            decoration: InputDecoration(
                hintText: "Enter Password",suffixIcon: IconButton(
                  icon: hidePassword == false
                      ? Icon(
                          Icons.visibility_rounded,color: Colors.purple,)
                      : Icon(
                          Icons.visibility_off_rounded,color: Colors.grey,),onPressed: () {
                    setState(() {
                      // here we change the value
                      // if it's false,it gets true
                      // and if it's true,it gets false
                      hidePassword = !hidePassword;
                    });
                  },);
  }
}
,

我已经尝试过你的代码,只要稍作改动就可以正常工作

class LoginPage extends GetView<LoginController>

同时将整个 textFormField 包裹在 Obx(()=>) 中

我在 Getx.i 中扩展了一个用于获取值和调用方法的控制器。如果您需要,我可以分享我的完整代码。

,

您需要将 Obx() 包裹在 TextFormField 中

Obx(() => TextFormField(...))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。