简体   繁体   中英

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. 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.

For example, this one will close itself after 4secs:

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


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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