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?
CodePudding user response:
You can use the Future.delayed
method to add a delay before dismissing a BarrierDismissible
in Flutter. Here's an example of how you can use it:
await showGeneralDialog(
context: context,
barrierDismissible: false,
barrierColor: Colors.black45,
transitionDuration: const Duration(milliseconds: 200),
pageBuilder: (BuildContext buildContext, Animation animation, Animation secondaryAnimation) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text("Delayed Dismiss"),
const Text("This dialog will dismiss after 2 seconds."),
ElevatedButton(
onPressed: () async {
await Future.delayed(const Duration(seconds: 2));
Navigator.of(context).pop();
},
child: const Text("Dismiss"),
),
],
),
);
},
);
In this example, the BarrierDismissible
is set to barrierDismissible: false
, so that it can't be dismissed by swiping or tapping outside the dialog. Then, when the user taps the "OK" button, the Future.delayed
method is used to add a delay of 2 seconds before calling Navigator.pop(context)
to dismiss the dialog.
CodePudding user response:
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')
),
),
),
),
);
},
);
},
),
)
);
}
}