Last active
September 4, 2021 19:53
-
-
Save rodydavis/572902859ff5985bfa4d47b29e18807a to your computer and use it in GitHub Desktop.
Flutter actions for confirm, alert and prompt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
/// Confirm with the user if they want to complete an action. | |
Future<bool> confirm(BuildContext context, String message, {String? title}) { | |
return showDialog<bool>( | |
context: context, | |
builder: (context) => AlertDialog( | |
title: Text(title ?? 'Confirm'), | |
content: Text(message), | |
actions: [ | |
TextButton( | |
child: const Text('No'), | |
onPressed: () => Navigator.of(context).pop(false), | |
), | |
TextButton( | |
child: const Text('Yes'), | |
onPressed: () => Navigator.of(context).pop(true), | |
), | |
], | |
), | |
).then((value) => value ?? false); | |
} | |
/// Show a dialog with a message. | |
Future<void> alert(BuildContext context, String message, {String? title}) { | |
return showDialog( | |
context: context, | |
builder: (context) => AlertDialog( | |
title: Text(title ?? 'Alert'), | |
content: Text(message), | |
actions: [ | |
TextButton( | |
child: const Text('Ok'), | |
onPressed: () => Navigator.of(context).pop(true), | |
), | |
], | |
), | |
); | |
} | |
/// Prompt the user to edit a value and fallback to the default value if canceled. | |
Future<String> prompt(BuildContext context, String value, {String? title}) { | |
return showDialog<String>( | |
context: context, | |
builder: (context) => _PromptDialog(title: title, value: value), | |
).then((val) => val ?? value); | |
} | |
class _PromptDialog extends StatefulWidget { | |
const _PromptDialog({ | |
Key? key, | |
required this.value, | |
required this.title, | |
}) : super(key: key); | |
final String value; | |
final String? title; | |
@override | |
_PromptDialogState createState() => _PromptDialogState(); | |
} | |
class _PromptDialogState extends State<_PromptDialog> { | |
late final _controller = TextEditingController(text: widget.value); | |
@override | |
Widget build(BuildContext context) { | |
return AlertDialog( | |
title: Text(widget.title ?? 'Prompt'), | |
content: TextField( | |
controller: _controller, | |
decoration: const InputDecoration( | |
hintText: 'Enter a value', | |
filled: true, | |
border: OutlineInputBorder(), | |
), | |
), | |
actions: [ | |
TextButton( | |
child: const Text('Cancel'), | |
onPressed: () => Navigator.of(context).pop(widget.value), | |
), | |
TextButton( | |
child: const Text('Save'), | |
onPressed: () => Navigator.of(context).pop(_controller.text), | |
), | |
], | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment