简体   繁体   English

Flutter:当你离开屏幕或按下返回时,你如何摆脱一个小部件?

[英]Flutter: How do you get rid of a widget when you leave the screen or press back?

I'm creating a simple chatting app and I've added some authentication validation.我正在创建一个简单的聊天应用程序,并添加了一些身份验证验证。 During login or registration, when I get an error message from firebase, a widget pops up displaying the error.在登录或注册期间,当我从 firebase 收到错误消息时,会弹出一个显示错误的小部件。 How do I make sure this widget goes away when I leave the screen?当我离开屏幕时,如何确保此小部件消失? Right now if I press back it goes to the welcome screen and when I go back to the login screen, the error is still there.现在,如果我按回它会进入欢迎屏幕,当我返回登录屏幕时,错误仍然存​​在。 Here's the widget-这是小部件-

class ErrorMessage extends StatefulWidget {
  @override
  _ErrorMessageState createState() => _ErrorMessageState();
}

class _ErrorMessageState extends State<ErrorMessage> {
  @override
  Widget build(BuildContext context) {
    if (error != null) {
      return Container(
        width: double.infinity,
        color: Colors.amberAccent,
        padding: EdgeInsets.all(8),
        child: Row(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.only(right: 8),
              child: Icon(Icons.error_outline),
            ),
            Expanded(
              child: Text(error, maxLines: 3),
            ),
            Padding(
              padding: EdgeInsets.only(left: 8),
              child: IconButton(
                icon: Icon(Icons.close),
                onPressed: () {
                  setState(() {
                    error = null;
                  });
                },
              ),
            ),
          ],
        ),
      );
    }
    return SizedBox(
      height: 0,
      width: 0,
    );
  }
}

Instead of using a custom made widget just for displaying error/warning messages, I suggest using something like awesome_dialog which already has autoHide capability.而不是使用只是为了显示错误/警告消息控件一个定制的,我建议使用类似awesome_dialog已经具有autoHide功能。

For example, this one will close itself after 4secs:例如,这个将在 4 秒后自行关闭:

AwesomeDialog(
    context: context,
    animType: AnimType.LEFTSLIDE,
    dismissOnTouchOutside: true,
    dismissOnBackKeyPress: true,
    headerAnimationLoop: true,
    dialogType: DialogType.WARNING,
    autoHide: Duration(seconds: 4),  
    body: Container(
      child: Center(
         child: Text(errorMessage, maxLines: 3),
      ),
    )


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM