AVEbrahimi
AVEbrahimi

Reputation: 19184

How to dismiss any open dialog in Flutter app, when app goes to background

In my Flutter app I have lots of pop up dialogs, but I need to dismiss any open dialog when app goes to background (user switches to another app).

I know about Lifecycle, but it's not easy to implement it for all dialogs.

Upvotes: 1

Views: 950

Answers (2)

Biruk Telelew
Biruk Telelew

Reputation: 1193

Navigator.of(context,rootNavigator:true).pop();

Upvotes: 0

Crazy Lazy Cat
Crazy Lazy Cat

Reputation: 15073

Did you try Navigator.popUntil on the life cycle?.

Navigator.popUntil(context, (route) => !(route is PopupRoute));

Example:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  void _showDialogs() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(title: Text("Dialog 1")),
    );
    showDialog(
      context: context,
      builder: (context) => AlertDialog(title: Text("Dialog 2")),
    );
    showDialog(
      context: context,
      builder: (context) => AlertDialog(title: Text("Dialog 3")),
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          child: Text("show multiple dialogs"),
          onPressed: _showDialogs,
        ),
      ),
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused)
      Navigator.popUntil(context, (route) => !(route is PopupRoute));
  }
}

Upvotes: 6

Related Questions