Как закрыть любой открытый диалог в приложении Flutter, когда приложение переходит в фоновый режим - PullRequest
1 голос
/ 06 февраля 2020

В моем приложении Flutter у меня много всплывающих диалогов, но мне нужно закрыть любой открытый диалог, когда приложение переходит в фоновый режим (пользователь переключается на другое приложение).

Я знаю о жизненном цикле, но это не так легко реализовать это для всех диалогов.

1 Ответ

4 голосов
/ 06 февраля 2020

Вы пробовали Navigator.popUntil в жизненном цикле?.

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

Пример:

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));
  }
}
...