Flutter - Delay barrierDismissible on dialog

332 Views Asked by At

In Flutter, use showGeneralDialog to show a dialog and use barrierDismissible to make it can not be closed when click outside.

But i want to make it can not be closed when click outside for first 2 second, then it can be able to close (barrierDismissible become true).

It seem easy with setState, but this 'showGeneralDialog' is a funtion.

How can i make it?

1

There are 1 best solutions below

1
On

Flutter declarative approach wasn't applied to this widget. Therefore you should do everything by yourself.

You can use showDialog() method and then go for your implementation by creating a global barrierDismissible variable and updating it after 2 seconds. The working solution for your approach is attached below:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: MyApp(),
      ),
    );

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool barrierDismissible = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body : Center(
        child: TextButton(
        child: const Text('Press the button'),
           onPressed: () {
          showDialog(
            context: context,
            builder: (BuildContext context) {
              barrierDismissible = false;
              Future.delayed(
                  const Duration(seconds: 2),
                  () => setState(() {
                        barrierDismissible = true;
                      }));
              return GestureDetector(
                onTap: () {
                  if (barrierDismissible) {
                    Navigator.of(context, rootNavigator: true).pop();
                  }
                },
                child: Material(
                  color: Colors.transparent,
                  child: GestureDetector(
                    onTap: () {},
                    child: Center(
                      child: Container(
                        padding: const EdgeInsets.all(20),
                        color: Colors.white,
                        child: const Text('Press Outside to close dialog after 2 seconds')
                      ),
                    ),
                  ),
                ),
              );
            },
            );
           },
        ),
      )
    );
  }
}