具有2 setState的Button onPressed异步方法

问题描述 投票:0回答:1

我不知道为什么异步onPressed方法中的2 setState导致错误

未处理的异常:在setpose()之后调用setState():_LoginScreenState#0eb2c(生命周期状态:已终止,未安装)

这是我的代码

 RaisedButton(
      child: Text('Login'),
      onPressed: emailController.text == "" || passwordController.text == ""
          ? null
          : () async {
              setState(() {
                _isLoading = true;
              });
              SharedPreferences prefs =
                  await SharedPreferences.getInstance();
              prefs.setString('email', emailController.text);
              try {
                await Provider.of<Auth>(context, listen: false)
                    .signIn(emailController.text, passwordController.text);
              } on HttpException catch (error) {
                exceptionAlertDialog(context, error.toString());
              } catch (error) {
                exceptionAlertDialog(context, error.toString());
              }
              setState(() {
                _isLoading = false;
              });
            },
    )

一旦isLoading为true,我将显示微调器。没有什么异常的

body: Container(
        alignment: Alignment.center,
        child: _isLoading
            ? Center(child: CircularProgressIndicator())
            : ListView(
                children: <Widget>[textSection(), buttonSection()],
              ),
      ),

如果我在onPressed按钮中注释掉那两个设置状态,一切都很好。

flutter dart
1个回答
1
投票

尝试放置isLoading处理

  @override
  void dispose() {
    _isLoading = false;
    super.dispose();
  }
© www.soinside.com 2019 - 2024. All rights reserved.