Skip to content

Instantly share code, notes, and snippets.

@rodydavis
Last active September 4, 2021 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodydavis/572902859ff5985bfa4d47b29e18807a to your computer and use it in GitHub Desktop.
Save rodydavis/572902859ff5985bfa4d47b29e18807a to your computer and use it in GitHub Desktop.
Flutter actions for confirm, alert and prompt
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