【问题标题】:How to change "setState()" when using GetX in Flutter?在 Flutter 中使用 GetX 时如何更改“setState()”?
【发布时间】:2022-01-03 23:26:43
【问题描述】:

我有一个如下所示的登录屏幕代码,其中有一个文本按钮,可将登录按钮的状态更改为注册或反向,并希望将其重写为使用GetX 库。但我不知道怎么做?

    enum AuthMode { Signup, Login }
    
    class AuthenticationScreen extends StatelessWidget {
      const AuthenticationScreen({Key? key}) : super(key: key);
      AuthMode _authMode = AuthMode.Login;

      @override
      Widget build(BuildContext context) {
        final GlobalKey<FormState> _formKey = GlobalKey();
    
        void _switchAuthMode() {
          if (_authMode == AuthMode.Login) {
             setState(() {
            _authMode = AuthMode.Signup;
=             });
            _controller!.forward();
          } else {
             setState(() {
            _authMode = AuthMode.Login;
             });
            _controller!.reverse();
          }
        }
    return Scaffold(
      body: Center(
        child: Container(
          constraints: const BoxConstraints(maxWidth: 400),
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
,
              TextButton(
                child: Text(
                    '${_authMode == AuthMode.Login ? 'SIGNUP' : 'LOGIN'} '),
                onPressed: _switchAuthMode,
                style: TextButton.styleFrom(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 30.0, vertical: 4),
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  textStyle: TextStyle(color: Theme.of(context).primaryColor),
                ),
            ],
          ),
        ),
      ),
    );

  }
}

我尝试了一些更改,例如将Authmode 转移到扩展GetxControllerauth_controller 文件并在AuthMode _authMode = AuthMode.Login; 之后添加obs 并尝试在_switchAuthMode() 中使用obx(()=&gt;),但没有成功。

【问题讨论】:

    标签: state setstate flutter-getx obs


    【解决方案1】:

    试试这样:

    final authMode= Rx<AuthMode>(AuthMode.Login);
    

    然后在你的switchAuthMode 方法上:

     authMode.value = AuthMode.Signup; // without setState
    

    最后,用Obx 包装Text 小部件:

     Obx(()=> Text('${authMode.value == AuthMode.Login ? 'SIGNUP' : 'LOGIN'} ')
    

    您实际上可以使您的小部件成为 StatelessWidget。

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 2021-01-22
      • 2020-06-29
      • 2022-11-09
      • 2021-11-11
      • 1970-01-01
      • 2022-11-27
      • 2021-05-11
      • 2021-07-06
      相关资源
      最近更新 更多